zoukankan      html  css  js  c++  java
  • leetcode面试准备:Kth Largest Element in an Array

    leetcode面试准备:Kth Largest Element in an Array

    1 题目

    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.
    接口:int findKthLargest(int[] nums, int k)

    2 思路

    找出数组中第k大的元素。
    分治的思想,利用partition的过程结果,第k的数,在排序后的len - k的位置。

    3 代码

           /**
    	 * 偷懒的做法
    	 */
    	public int findKthLargest0(int[] nums, int k) {
    		Arrays.sort(nums);
    		return nums[nums.length - k];
    	}
    	
    	/**
    	 * 分治的思想,利用partition的过程结果,第k的数,在排序后的len - k的位置。 
    	 */
    	public int findKthLargest(int[] nums, int k) {
    		int len = nums.length;
    		int goal = len - k;
    		int left = 0, right = len - 1;
    		int index = partition(nums, left, right);
    		while (index != goal) {
    			if (index < goal) {
    				left = index + 1;
    			} else {
    				right = right - 1;
    			}
    			index = partition(nums, left, right);
    		}
    		return nums[goal];
    
    	}
    
    	private int partition(int[] a, int p, int r) {
    		int i = p - 1;
    		int x = a[r];
    		for (int j = p; j < r; j++) {
    			if (a[j] <= x) {
    				i++;
    				swap(a, i, j);
    			}
    		}
    		swap(a, i + 1, r);
    		return i + 1;
    	}
    
    	private void swap(int[] a, int i, int j) {
    		int tmp = a[i];
    		a[i] = a[j];
    		a[j] = tmp;
    	}
    
    

    4 总结

    分治

  • 相关阅读:
    Java中的Iterable与Iterator详解
    1、JAVA数据类型
    maven 国内阿里云镜像配置
    数据库优化以及SQL优化小结
    用IDEA生成javadoc文档
    Elastic Search 新手笔记(1)——入门篇
    MQ技术选型
    springboot + aop + Lua分布式限流的最佳实践
    go 变量声明作用域问题
    android 开发环境变量配置
  • 原文地址:https://www.cnblogs.com/byrhuangqiang/p/4801009.html
Copyright © 2011-2022 走看看