Quick Sort : 时间复杂度为O(logn)
思路:参考https://www.cnblogs.com/luomeng/p/10587492.html
public void quickSort(int[] nums, int low, int high) {
if (low >= high) {
return;
}
int pivot = partition(nums, low, high);
quickSort(nums, low, pivot - 1);
quickSort(nums, pivot + 1, high);
}
public int partition (int[] nums, int low, int high) {
int temp = nums[low];
while (low < high) {
while (low < high && nums[high] >= temp) {
high--;
}
nums[low] = nums[high];
while (low < high && nums[low] <= temp) {
low++;
}
nums[high] = nums[low];
}
//退出循环时,low==high,此时的位置即为pivot的位置
nums[high] = temp;
return high;
}
(一)kth largest element in an array
https://leetcode.com/problems/kth-largest-element-in-an-array/description/
题目:在无序数组中找到第k大的元素;
解答:使用快速选择算法。在数组中随机找到一个pivot元素,将比它大的数移动到其左边,比它小的数移动到其右边。这样pivot在移动完成后的数组中的位置x则表明它是第x大的元素。此时的left = x + 1或 x,right = x - 1 或 x。第k大的元素应该处于start + k -1的位置,若该位置比left大,说明第k大元素比pivot小,则在x右边继续搜索(此时变成搜索第(start + k - 1 - (left - 1)= start + k - left);若该位置比right小,说明第k大元素比pivot大,则在x左边继续搜索。
代码:
class Solution {
public int findKthLargest(int[] nums, int k) {
return quickSelect(nums, 0, nums.length - 1, k);
}
private int quickSelect(int[] nums, int start, int end, int k) {
int left = start, right = end;
int pivot = nums[(left + right) /2];
while (left <= right) {
while (left <= right && nums[left] > pivot) {
left++;
}
while (left <= right && nums[right] < pivot) {
right--;
}
if (left <= right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
if (start + k - 1 <= right) {
return quickSelect(nums, start, right, k);
}
if (start + k - 1 >= left) {
return quickSelect(nums, left, end, k - (left - start));
}
return nums[right + 1];
}
}
(二)median of two sorted arrays
https://leetcode.com/problems/median-of-two-sorted-arrays/description/
题目:求两个已排序序列的中位数,要求时间复杂度为O(log(n + m))。若总长度为偶数,返回中间两个数的平均值;
解答:使用与quick sort类似的思想,相当于递归查找第k大的元素。比较两个数组的第k/2元素的大小,将较小的那个数组前k/2的部分舍去,继续进行查找。如果某个数组长度达不到 k /2, 则将另一个数组里的元素舍弃(可用Integer.MAX_VALUE来简化实现)。注意!!需要考虑start大小超出nums数组长度的情况!
代码:
class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int lenSum = nums1.length + nums2.length;
if (lenSum % 2 == 1) {
return findKth(nums1, 0, nums2, 0, lenSum / 2 + 1);
} else {
return (findKth(nums1, 0, nums2, 0, lenSum / 2 + 1) + findKth(nums1, 0, nums2, 0, lenSum / 2)) / 2.0;
}
}
private int findKth(int[] nums1, int start1, int[] nums2, int start2, int k) {
int end1 = start1 + k / 2 - 1;
int end2 = start2 + k / 2 - 1;
int pivot1 = Integer.MAX_VALUE;
int pivot2 = Integer.MAX_VALUE;
if (start1 >= nums1.length) {
return nums2[start2 + k - 1];
}
if (start2 >= nums2.length) {
return nums1[start1 + k - 1];
}
if (k == 1) {
return Math.min(nums1[start1], nums2[start2]);
}
if (end1 < nums1.length) {
pivot1 = nums1[end1];
}
if (end2 < nums2.length) {
pivot2 = nums2[end2];
}
if (pivot1 < pivot2) {
return findKth(nums1, end1 + 1, nums2, start2, k - k / 2);
} else{
return findKth(nums1, start1, nums2, end2 + 1, k - k / 2);
}
}
}