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);
		}
	}

猜你喜欢

转载自blog.csdn.net/tiaochewang219/article/details/84891427