问题:给定一个数组,求第k大的元素
分析:题目可以转换成排序的问题,因为排序好的数组查询很方便。。
惯性思维的解法(超出时间):
从左到右遍历得到最小的元素放在左边
class Solution {
/*
* @param k : description of k
* @param nums : array of nums
* @return: description of return
*/
public int kthLargestElement(int k, int[] nums) {
// write your code here
commonSort(nums);
return nums[nums.length - k];
}
public int[] commonSort(int[] nums) {
for (int i=0; i<nums.length; i++) {
for (int j=i + 1; j<nums.length; j++) {
if (nums[i] >= nums[j]) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
return nums;
}
}
冒泡排序解法(
超出时间):
class Solution {
/*
* @param k : description of k
* @param nums : array of nums
* @return: description of return
*/
public int kthLargestElement(int k, int[] nums) {
// write your code here
bbSort(nums);
// quickSort(nums, 0, nums.length - 1);
return nums[nums.length - k];
}
/**
* 冒泡排序(从小到大):
* 两两比较,大的放右边。
* 如[3, 5, 4, 2, 6]进行冒泡排序:
* 1. 3和5比较,不交换
* 2. 5和4比较,交换[3,4,5,2,6]
* 3. 5和2比较,交换[3,4,2,5,6]
* 4. 5和6比较,不交换
* --------------------
* 5. 3和4比较,不交换
* 6. 4和2比较,交换[3,2,4,5,6]
* 7. 4和5比较,不交换
* --------------------
* 8. 3和2比较,交换[2,3,4,5,6]
* 9. 3和4比较,不交换
* --------------------
* 10. 2和3比较,不交换
*/
public int[] bbSort(int[] nums) {
for (int i=0; i<nums.length; i++) {
for (int j=0; j<nums.length-i-1; j++) {
if (nums[j] >= nums[j+1]) {
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
}
}
return nums;
}
}
快速排序的解法:
class Solution {
/*
* @param k : description of k
* @param nums : array of nums
* @return: description of return
*/
public int kthLargestElement(int k, int[] nums) {
// write your code here
// bbSort(nums);
quickSort(nums, 0, nums.length - 1);
return nums[nums.length - k];
}
/**
* 快速排序:
* 分而治之的比较排序算法:
* 思想是选定一个基准元素,将大于基准元素的数字放在基准元素右边,小于基准元素的数字放在基准元素左边,然后递归左边和右边的数组
*/
public void quickSort(int arr[],int _left,int _right) {
int left = _left;
int right = _right;
int temp = 0;
if (left <= right) { // 递归执行条件
temp = arr[left]; // 第一个元素作为基准元素
while (left != right) {
while (right > left && arr[right] >= temp)
right--;
arr[left] = arr[right];
while (left < right && arr[left] <= temp)
left++;
arr[right] = arr[left];
}
// 此时left = right
arr[left] = temp; // 基准元素放在中间
quickSort(arr, _left, left - 1); // 基准元素左边递归
quickSort(arr, right + 1, _right); // 基准元素右边递归
}
}
}
耍无赖的解法,事实上Arrays.sort()使用的算法就是快排:
class Solution {
/*
* @param k : description of k
* @param nums : array of nums
* @return: description of return
*/
public int kthLargestElement(int k, int[] nums) {
// write your code here
Arrays.sort(nums); // 排序
return nums[nums.length - k];
}
};