分治法求第k大元素java
时间: 2024-06-03 13:09:26 浏览: 92
可以使用快速选择算法来求解第k大元素,时间复杂度为O(n),具体实现可以参考以下代码:
public static int quickSelect(int[] nums, int k) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int pivotIndex = partition(nums, left, right);
if (pivotIndex == nums.length - k) {
return nums[pivotIndex];
} else if (pivotIndex < nums.length - k) {
left = pivotIndex + 1;
} else {
right = pivotIndex - 1;
}
}
return -1;
}
public static int partition(int[] nums, int left, int right) {
int pivot = nums[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (nums[j] <= pivot) {
i++;
swap(nums, i, j);
}
}
swap(nums, i + 1, right);
return i + 1;
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
阅读全文