您的位置:首页 > 编程语言 > Java开发

lintcode刷题记录合并排序数组 java

2017-12-14 22:48 260 查看
在数组中找到第k大的元素


 注意事项


你可以交换数组中的元素的位置

给出数组 
[9,3,2,4,8]
,第三大的元素是 
4


给出数组 
[1,2,3,4,5]
,第一大的元素是 
5
,第二大的元素是 
4
,第三大的元素是 
3
,以此类推

你的输入
3
[9,3,2,4,8]


你的输出
4


期望答案
4


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
if(k > nums.length){
return -1;
}else{
//bubbleSort(nums);//冒泡排序
quickSort(nums, 0, nums.length-1);
return nums[k-1];
}
}

//冒泡排序没过审核,5555555就会这一个
public static void bubbleSort(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[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
}
}

//快速排序
public static void quickSort(int[] nums, int start, int end){

if(start < end){
int position = partition(nums, start, end);
quickSort(nums, start, position-1);
quickSort(nums, position+1, end);
}
}

//快速排序分区从大到小排列
public static int partition(int[] nums, int start, int end){
//快速排序选择基数三种方式:固定选值;随机选值;三数取中
//三数取中
int mid = start + (end - start)/2;
if(nums[mid] < nums[end]){
swap(nums[mid], nums[end]);
}
if(nums[start] < nums[end]){
swap(nums[start], nums[end]);
}
if(nums[mid] < nums[start]){
swap(nums[mid], nums[start]);
}
int key = nums[start];
while(start<end){
while(nums[end]<=key && start<end){
end--;
}
nums[start] = nums[end];
while(nums[start]>=key && start<end){
start++;
}
nums[end] = nums[start];
}
nums[end] = key;
return end;
}

public static void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: