题目链接:LeeCode215数组中的第k个最大元素
题目描述:
这个题我必须吐槽一下,我拿到手看题目,不知道是我理解问题还是怎么的,我就感觉他是不让排序然后做出来,我整整想了两个小时,凑了一个,你没听错就是凑,凑一个不用动数组的方法,结果一运行要我半条命,代码我贴出来留念,千万别学这种
class Solution {
public static int findKthLargest(int[] nums, int k) {
List<Integer> small=new ArrayList<>();
List<Integer> big=new ArrayList<>();
List<Integer> list=new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
list.add(nums[i]);
}
return findst(small,big,list,0,k,0);
}
public static int findst(List<Integer> small,List<Integer> big,List<Integer> list,int st,int k,int bigg){
small.clear();
big.clear();
if(list.size()==1)return list.get(0);
int poll = list.get(0);
for (int i = 1; i < list.size(); i++) {
if(poll>list.get(i)) small.add(list.get(i));
else big.add(list.get(i));
}
st=list.size()-small.size()+bigg;
//System.out.println(small);
if(st>k) return findst(small, big, new ArrayList<>(big), st, k,bigg);
else if(st<k){
bigg+=big.size()+1;
return findst(small, big, new ArrayList<>(small), st, k,bigg);
}
else return poll;
}
}
然后就是因为太慢了,我就想看看题解大神都是怎么写的,好家伙,又是快排又是优先队列,还有甚者直接调库函数。然后我就写了一个归并,速度直接就上来了。
import java.util.PriorityQueue;
public class Solution {
public static int findKthLargest(int[] nums, int k) {
sortmerge(nums,0,nums.length-1,new int[nums.length]);
return nums[nums.length-k];
}
public static void merge(int[] nums,int start,int mid,int end,int[] temp){
int left=start,right=mid+1,index= start;
while (left <= mid && right <= end) {
if(nums[left]>nums[right])temp[index++]=nums[right++];
else temp[index++]=nums[left++];
}
while(left<=mid)temp[index++]=nums[left++];
while (right<=end)temp[index++]=nums[right++];
for (int i = start; i <=end; i++) {
nums[i]=temp[i];
}
}
public static void sortmerge(int[] nums,int start,int end,int[] temp){
if (start < end) {
int mid=(start+end)/2;
sortmerge(nums,start,mid,temp);
sortmerge(nums, mid+1, end,temp);
merge(nums,start,mid,end,temp);
}
}
}
然后我又想直接排序是不是不太好,毕竟大家都非常隐含的快排“思想”,优先队列,所以我也用快排思想写了一个
import java.util.PriorityQueue;
public class Solution {
public static int findKthLargest(int[] nums, int k) {
return quicksort(nums,0, nums.length-1,k);
}
public static void swap(int[] nums,int i,int j){
int temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
public static int quicksort(int[] nums,int start,int end,int k){
int l=start,r=end,mark=nums[start];
while (l != r) {
while(nums[r]>=mark&&l<r)r--;
swap(nums,l,r);
while(nums[l]<=mark&&l<r)l++;
swap(nums,l,r);
}
if(nums.length-l>k) return quicksort(nums, l+1, end, k);
else if(nums.length-l<k) return quicksort(nums,start,l-1,k);
else return nums[nums.length-k];
}
}
又用优先队列写了一个
import java.util.PriorityQueue;
public class Solution {
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> queue=new PriorityQueue<>();
for (int i = 0; i < nums.length; i++) {
queue.offer(nums[i]);
}
for (int i = 0; i < nums.length - k; i++) {
queue.poll();
}
return queue.peek();
}
}