Given an integer array, find the top k largest numbers in it.
Example
Given [3,10,1000,-99,4,100]
and k = 3
.
Return [1000, 100, 10]
.
解法一:
1 class Solution { 2 public: 3 /* 4 * @param nums: an integer array 5 * @param k: An integer 6 * @return: the top k largest numbers in array 7 */ 8 vector<int> topk(vector<int> nums, int k) { 9 std::priority_queue<int> heap; 10 for(int i = 0; i < nums.size(); i++) { 11 heap.push(nums[i]); 12 } 13 14 std::vector<int> result; 15 for (int i = 0; i < k; i++) { 16 result.push_back(heap.top()); 17 heap.pop(); 18 } 19 20 return result; 21 } 22 };
优先队列,类似于维护一个大小为k的最大堆/最小堆(STL中的priority_queue默认是最大堆),时间复杂度为O(n * logk)
解法二:
1 class Solution { 2 /* 3 * @param nums an integer array 4 * @param k an integer 5 * @return the top k largest numbers in array 6 */ 7 public int[] topk(int[] nums, int k) { 8 int[] temp = new int[k]; 9 if(nums == null || nums.length == 0) { 10 return temp; 11 } 12 quickSort(nums, 0, nums.length - 1, k); 13 14 if(nums.length < k) { 15 return nums; 16 } 17 18 for(int i = 0; i < k; i++) { 19 temp[i] = nums[i]; 20 } 21 22 return temp; 23 } 24 25 public void quickSort(int[] nums, int start, int end, int k) { 26 if (start >= end) { 27 return; 28 } 29 30 int left = start, right = end; 31 int mid = left + (right - left) / 2; 32 int pivot = nums[mid]; 33 34 while(left <= right) { 35 while(left <= right && nums[left] > pivot) { 36 left++; 37 } 38 39 while(left <= right && nums[right] < pivot) { 40 right--; 41 } 42 43 if(left <= right) { 44 swap(nums, left, right); 45 left++; 46 right--; 47 } 48 } 49 50 quickSort(nums, start, right, k); 51 quickSort(nums, left, end, k); 52 } 53 54 private void swap(int[] nums, int left, int right) { 55 int temp = nums[left]; 56 nums[left] = nums[right]; 57 nums[right] = temp; 58 } 59 };
快速排序,取出前k大的数,时间复杂度O(n*logn + k)