leetcode215java代码小问题

来源:1-1 算法面试不仅仅是正确的回答问题

不考过程序员不改名字

2021-05-31

class Solution {
    public int findKthLargest(int[] nums, int k) {
        quickSort1(nums,0,nums.length-1);
        int count = 0;
        for (int i = nums.length-1;i>=0;i--){
            count++;
            if (count==k){
                return nums[i];
            }
        }
        return 0;
    }
        public static void quickSort1(int[] num,int low,int high){
        if(high<low){
            return;
        }
        int start = low;
        int end = high;
        int base = num[low];
        int t;
        while (start<end){
            while (start<end&&num[end]>=base){
                end--;
            }
            while (start<end&&num[start]<=base){
                start++;
            }
            if (start<end){
                t = num[end];
                num[end] = num[start];
                num[start] = t;
            }
        }
        num[low] = num[end];
        num [end] = base;
        quickSort1(num,low,start-1);
        quickSort1(num,start+1,high);
    }
}

老师,为什么我写的快排效率那么低啊,有什么优化的思路可以提供一下嘛

写回答

1回答

liuyubobobo

2021-06-01

使用快排的思想,对于这个问题,一个典型的优化思路是,我们不需要对整个数组进行排序。比如我们是从大到小排序,找到第 3 大的元素,在 partition 的过程中,如果标定点的位置是 5,那么第三大的元素,已经不可能出现在 5 以后了,所以对 5 以后的数组根本不需要排序,只需要看 5 以前的数组就好。


如果是从小到大排序,是同理的,只不过对索引做一下转换。(第 1 大元素等于找排序后索引为 n - 1 的元素,以此类推。)


对于这个思路我的 C++ 实现参考代码:https://github.com/liuyubobobo/Play-Leetcode/blob/master/0001-0500/0215-Kth-Largest-Element-in-an-Array/cpp-0215/main3.cpp

注意 35-38 的代码,我们只需要选择一个方向继续递归就好,不需要两个方向都递归,对整个数组完成排序。


继续加油!:)

0
1
不考过程序员不改名字
好嘞,明白了,谢谢老师
2021-06-01
共1条回复

玩转算法面试-- Leetcode真题分门别类讲解

课程配套大量BAT面试真题,高频算法题解析,强化训练

7446 学习 · 1159 问题

查看课程