//move the k largest elements to the left part of array publicclassSolution { publicintfindKthLargest(int[] nums, int k) { if (nums.length == 1) return nums[0];
intleft=0; intright= nums.length - 1;
while (left <= right) { intpivotPos= partition(nums, left, right); if (pivotPos - left + 1 < k) { k = k - (pivotPos - left + 1);// shrink k value left = pivotPos + 1;// move left to pivotPos + 1 } elseif (pivotPos - left + 1 > k) { right = pivotPos - 1;// shrink right by 1 at least } else { return nums[pivotPos]; } } return0; }
// make elements value between [0, leftBound] are all >= pivot privateintpartition(int[] array, int left, int right) { intpivotIndex= left + (right - left) / 2; intpivot= array[pivotIndex]; swap(array, pivotIndex, right);
classSolution { publicintremoveDuplicates(int[] nums) { inti=0; for (int n : nums) if (i < 2 || n > nums[i - 2]) nums[i++] = n; return i; } }
补充解答:修改版
1 2 3 4 5 6 7
intremoveDuplicates(vector<int>& nums,int k) { if(nums.size()<k) return nums.size(); // if array size is less than k then return the same int i,j; for(i=k,j=k ; i<nums.size();i++) if(nums[j-k]!=nums[i]) nums[j++]=nums[i]; return j; }
这个解答,可以适用于保留最多不超过 K 个相同的元素。
和第一种解法的思路相似,j-k 就是 lookback,向后看。第一种解法是 nums[i-2],往后看两位。现在是往后看 k 位。