Leetcode_215_Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note:
You may assume k is always valid, 1 ? k ? array’s length.

Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.

題目大意:
給一個無序的數組,要求找到第k大的數字。
思路:
既然找第k大個元素的位置,就是找到第(length-k)個元素,這裏可以使用快速排序的思想,快速排序特性是每一趟結束之後可以確定一個元素的位置。
1. 取一個基準p(一般是數組的第一個元素)。
2. 進行快速排序一趟之後可以確定這個基準的最終位置 loc。
3. 如果loc大於(length-k)那就在左邊找,否則就在右邊找。

   public int findKthLargest(int[] nums, int k) {
        if(nums.length==0){
            return 0;
        }
        if(k<0 || k>nums.length){
            return -1;
        }
        //上面排除了錯誤的例子。下面正式開始。
        int left=0;
        int right=nums.length-1;
        int taget=nums.length-k;
        int i=0;
        while (left<=right){//如果左邊小於右邊
            i=quickSort(nums,left,right);  //找到基準的最終的位置
            if(i==taget){//如果等於target的話就跳出
                break;
            }else if(i<taget){//如果i<target的話就在右邊找。
                left=i+1;
            }else {
                right=i-1;
            }
        }
        return nums[i];//nums[i]就是我們要找的元素。
    }
    public int quickSort(int []nums,int left,int right){//返回值是 基準的 最終位置loc。
        int tmp;
        int i=left;
        int j=right;
        tmp=nums[left];
        while (i!=j){
            while (j>i&&nums[j]>tmp) --j;
            if(i<j){
                nums[i]=nums[j];
                ++i;
            }
            while (i<j && nums[i]<tmp) ++i;
            if(i<j){
                nums[j]=nums[i];
                --j;
            }
        }
        nums[i]=tmp;

        return i;

    }

分析:使用快速排序的思路進行最大值的挑選速度很快。還可以用其他的方法,歸併樹。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章