链接:https://leetcode.com/tag/divide-and-conquer/

 

【4】Median of Two Sorted Arrays 

【23】Merge k Sorted Lists 

 

【53】Maximum Subarray (2019年1月23日, 谷歌tag复习)

最大子段和。

题解:

follow up 是divide and conquer

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. 

 

【169】Majority Element 

 

【215】Kth Largest Element in an Array (2018年12月11日,wiggle sort 专题,需要复习)

用 O(n) 的时间复杂度找到数组中第 K 大的元素。重复元素也计入 K。

题解:本题可以用 heap 解答,时间复杂度是 O(nlogK)。其实还可以用 quick select 解答(也就是快排的partition(2-way partition)),平均复杂度是 O(n),最坏是 O(n^2)。为了搞平均,一开始要把数组 random_shuffle 一下,尽可能避免 worst case。 

 1 class Solution {
 2 public:
 3     int findKthLargest(vector<int>& nums, int k) {
 4         random_shuffle(nums.begin(), nums.end());
 5         const int n = nums.size();
 6         int start(0), end(n-1), index(n-k);        
 7         while (start < end) {
 8             int idx = partition(nums, start, end);
 9             if (idx < index) {
10                 start = idx + 1;
11             } else if (idx > index) {
12                 end = idx - 1;
13             } else {
14                 return nums[idx];
15             }
16         }
17         return nums[start];
18     }
19     int partition(vector<int>& nums, int start, int end) {
20         int pivot = start;
21         while (start < end) {
22             while (nums[start] <= nums[pivot]) {
23                 start++;
24             }
25             while (nums[end] > nums[pivot]) {
26                 end--;
27             }
28             if (start > end) {break;}
29             swap(nums[start], nums[end]);
30         }
31         swap(nums[end], nums[pivot]);
32         return end;
33     }
34 
35 };
View Code

相关文章: