Leetcode---数组中的第K个最大元素--随机化算法

数组中的第K个最大元素

题目链接:数组中的第K个最大元素

思路:
  • 如果先排序,不管利用哪个,比较排序时间复杂度最优为O(nlgn)
  • 但是我们发现,快排的一趟排列有一定的性质,我们可以求得一趟快排之后,该数在整个数组中排在第几位,且将整个数组划分为两段
  • 利用这个性质,我们可以单侧截断,递归查找第K个最大元素
  • 但是这个算法并不是最优的,因为他和数组的原始状况有关,原始数组最坏为逆序状态下,算法复杂度为O(n ^2)
  • 改进时加入随机化算法,不直接将第一个元素作为关键数,而是随机产生数组中的一个数作为关键数
public static int findKthLargest(int[] nums, int k) {
		return sort(nums,0,nums.length-1,k);
    }
	public static int sort(int[] nums,int first,int last,int k) {
        //在范围内产生随机数,和第一个数字交换
		int exch = (int) (first+Math.random()*(last-first+1));
		int temp_exc = nums[exch];
		nums[exch] = nums[first];
		nums[first] = temp_exc;
		//记录第一个数字
		int temp = nums[first];
		int rear = last,front = first;
		while(front<rear) {
			//从后往前找小数
			while(nums[rear]>=temp&&front<rear)rear--;
//			System.out.println(rear);
			//此时找到第一个小数
			nums[front] = nums[rear];
			while(nums[front]<=temp&&front<rear)front++;
//			System.out.println(front);
			//此时找到第一个大数
			nums[rear] = nums[front];
		}
		nums[front] = temp;	
//		for(int n:nums) {
//			System.out.print(n+"  ");
//		}
		if(last-front+1==k) {
			return nums[front];
		}else if(last-front+1>k) {
			return sort(nums, front+1, last, k);
		}else {
			return sort(nums, first, front-1, k-last+front-1);
		}
	}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值