这种算法的均摊复杂度是o(n)
T(n) = T(n/2) + o(n)
= T(n/4) + 0(n/2)+o(n)
=...
= 0(n)
Kth largest element 问题
1 public class Solution { 2 public int findKthLargest(int[] nums, int k) { 3 if (nums == null || nums.length == 0) { 4 return -1; 5 } 6 return helper(nums, nums.length - k + 1, 0, nums.length - 1); //length - k + 1 convert the kth large to k‘th small one 7 } 8 private int helper(int[] nums, int k, int start, int end) { 9 if (start == end) { 10 return nums[start]; 11 } 12 int position = partition(nums, start, end); 13 if (position + 1 == k) { 14 return nums[position]; 15 }else if (position + 1 > k) { 16 return helper(nums, k, start, position - 1); //这个地方为什么是return 下一层递归的结果,因为需要的结果在下层/下下层递归中得到, 把这个值返回来交给最上面的一层 17 } else { 18 return helper(nums, k, position + 1, end); 19 } 20 } 21 22 private int partition(int[] nums, int left, int right) { 23 int pivot = nums[left]; 24 while (left < right) { 25 while (left < right && nums[right] >= pivot) { 26 right--; 27 } 28 nums[left] = nums[right]; 29 while (left < right && nums[left] <= pivot) { 30 left++; 31 } 32 nums[right] = nums[left]; 33 } 34 nums[left] = pivot; 35 return left; 36 } 37 }
时间: 2024-10-12 15:55:12