数组当中的第K大元素

一个没有排序数组当中的第K大元素,

  1. 选择排序
  2. 优化的选择排序

过程

class Solution {
    public int findKthLargest(int[] nums, int k) {
       if (nums == null || nums.length == 0 || k <= 0 || k > nums.length) {
            return 0;
        }
         return select(nums, 0, nums.length - 1, nums.length - k);
    }
    public int select(int[] nums, int left, int right, int k) {
    
        while(left<right){
            int pivotIndex = partition(nums, left, right);
        
        if (pivotIndex == k) {
            return nums[pivotIndex];
        } 
        else if(pivotIndex < k) {
            //在这里还是不要变k , 因为是从右变开始算起的, 如果是
            left = pivotIndex+1;
           
        }  else
        {
         right  =  pivotIndex-1;
            
        }
        }
        return nums[left];
    }
       
 public int partition(int[] array, int low, int high) {

        int pivot = array[low];                  
        int i = low, j = high;                   
        while (i < j) {                          
            while (i < j && array[j] >= pivot) { 
             --j;                             
           }                                    
            array[i] = array[j];                 
            while (i < j && array[i] <= pivot) { 
            ++i;                             
          }                                    
             array[j] = array[i];                 
         // return partation                  
        }
         array[i] = pivot;                        
         //the position                           
         return i;   
    }
}

进行优化

对上述数组进行一个随机优化即可解决该问题

private void shuffle(int a[]) {

        final Random random = new Random();
        for(int ind = 1; ind < a.length; ind++) {
            final int r = random.nextInt(ind + 1);
            exch(a, ind, r);
        }
    }

完整代码

public int findKthLargest(int[] nums, int k) {

        shuffle(nums);
        k = nums.length - k;
        int lo = 0;
        int hi = nums.length - 1;
        while (lo < hi) {
            final int j = partition(nums, lo, hi);
            if(j < k) {
                lo = j + 1;
            } else if (j > k) {
                hi = j - 1;
            } else {
                break;
            }
        }
        return nums[k];
    }

private void shuffle(int a[]) {

        final Random random = new Random();
        for(int ind = 1; ind < a.length; ind++) {
            final int r = random.nextInt(ind + 1);
            exch(a, ind, r);
        }
    }

时间复杂度可以优化为O(N) 时间复杂度

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值