Leetcode 排序
Leetcode 75
75. Sort Colors
Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Follow up:
Could you solve this problem without using the library’s sort function?
Could you come up with a one-pass algorithm using only O(1) constant space?
Example 1:
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
- 思路:
使用三路快排算法(递归版),此处要注意递归时边界指针的意义。
void QuickSort3Ways(vector<int>& nums, int low, int high) {
if (low >= high)
return;
int lt = low;
int gt = high;
int i = lt + 1;
int temp = nums[lt];
// nums[low, lt -1] < temp
// nums[gt + 1, high] > temp
// nums[lt, gt] == temp
while (i <= gt) {
if (nums[i] < temp) {
swap(nums[i++], nums[lt++]);
} else if (nums[i] > temp) {
swap(nums[i], nums[gt--]);
} else {
i++;
}
}
QuickSort3Ways(nums, low, lt - 1);
QuickSort3Ways(nums, gt + 1, high);
}
void sortColors(vector<int>& nums) {
int low = 0;
int high = nums.size() - 1;
QuickSort3Ways(nums, low, high);
}
Leetcode 215
215. Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
- 思路:
使用双路快排来对数组进行排序,当分割点位置等于size - k时即可停止排序,得到答案。
void QuickSort2Ways(vector<int>& nums, int low, int high, int target) {
int lt = low + 1;
int gt = high;
int temp = nums[low];
while (true) {
// 此处对于指针位置的比较要在值比较之前,
// 否则在求解[1]时会lt出现越界。
while (gt > low && nums[gt] > temp) gt--;
while (lt < high && nums[lt] < temp) lt++;
// 此处gt <= lt,否则排序[8,6,6]时结果为[6,8,6]。
if (gt <= lt) break;
swap(nums[lt++], nums[gt--]);
}
swap(nums[low], nums[gt]);
if (gt > target)
QuickSort2Ways(nums, low, gt - 1, target);
else if(gt < target)
QuickSort2Ways(nums, gt + 1, high, target);
else
return;
}
int findKthLargest(vector<int>& nums, int k) {
int index = nums.size() - k;
QuickSort2Ways(nums, 0, nums.size() - 1, index);
return nums[index];
}
Leetcode 88
88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
- 思路:
使用归并查找中的归并过程。
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
vector<int> res(m + n, 0);
int start1 = 0;
int start2 = 0;
int k = 0;
while (start1 < m && start2 < n) {
res[k++] =
nums1[start1] < nums2[start2] ? nums1[start1++] : nums2[start2++];
}
while (start1 < m)
res[k++] = nums1[start1++];
while (start2 < n)
res[k++] = nums2[start2++];
nums1 = res;
}