LeetCode interview questions 17.14, minimum number of K

Title description

https://leetcode-cn.com/problems/smallest-k-lcci/
Insert picture description here

solution

Use quick sort, and then according to the input K, we decide which side to recurse next:

class Solution {
    
    
    public int[] smallestK(int[] arr, int k) {
    
    
        if(arr.length==0) return new int[0];
        int []res = new int[k];
        quickSort(arr,0,arr.length-1,k);
        for(int i=0;i<k;i++){
    
    
            res[i] = arr[i];
        }
        return res;

    }
    public void quickSort(int[]num,int start,int end,int k){
    
    
        int base = num[start];
        int i = start,j=end;
        while(i<j){
    
    
            while(i<j && num[j]>base){
    
    
                j--;
            }
            while(i<j && num[i]<base){
    
    
                i++;
            }
            if( num[i]==num[j] && i<j){
    
    
                i++;
            }else{
    
    //使用异或交换两个数,从小到达排序
             if(num[i]!=num[j]){
    
    //必须要判断喔
                    num[i] = num[i]^num[j];
                    num[j] = num[i]^num[j];
                    num[i] = num[i]^num[j];
             }
            
            }
        }
        if(i==k-1)//表示现在我们要找的是左边
            return;//已经找够了k个最小的数了
        else if(i-1>start && i>k-1){
    
    //只需要排左边
            quickSort(num,start,i-1,k);//
        }
        else if(j+1<end && i<k-1) {
    
    //注意这里
            quickSort(num,j+1,end,k);
        }

    }
}

Insert picture description here
Here I encountered a problem:

 if(nums[i]!=nums[j]){
    
    //使用之前注意判断是否已经相同了
                    nums[i] = (nums[i])^(nums[j]);
                    nums[j] = (nums[i])^(nums[j]);
                    nums[i] = (nums[i])^(nums[j]);
                }

If you want to pretend to be forced, remember to add it to judge whether it is equal, if it is equal, then you will always get 0.

In the solution, of course, you can use the sort directly, and then take the top k numbers. But fast sorting is much more efficient.

Guess you like

Origin blog.csdn.net/qq_44861675/article/details/114679522