zoukankan      html  css  js  c++  java
  • *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.

    解法:quick select

    参考Algorithm课quick sort的笔记

     
    public class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (k < 1 || nums == null) {
            return 0;
        }
     
        return getKth(nums.length - k +1, nums, 0, nums.length - 1);
    }
     
    public int getKth(int k, int[] nums, int start, int end) {
     
        int pivot = nums[end];
            int storeIndex = start;        
            for (int i = start; i < end; i++) {
                if (nums[i] < pivot) {
                    swap(nums, storeIndex, i);
                    storeIndex++; // 交换位置后,storeIndex 自增 1,代表下一个可能要交换的位置
                }
            }
            swap(nums, end, storeIndex); // 将基准元素放置到最后的正确位置上
        
     
        if (k == storeIndex + 1) {
            return pivot;
        } else if (k < storeIndex + 1) {
            return getKth(k, nums, start, storeIndex - 1);
        } else {
            return getKth(k, nums, storeIndex + 1, end);
        }
    }
     
    public void swap(int[] nums, int n1, int n2) {
        int tmp = nums[n1];
        nums[n1] = nums[n2];
        nums[n2] = tmp;
    }
    }
  • 相关阅读:
    kafka学习笔记:知识点整理
    java操作hbase 增删改查
    json往前台送数据中文乱码
    17年数据结构笔记
    设置MYSQL数据库编码为UTF-8
    c++的 struct和class
    算法之arrays and strings
    对于快速排序的理解
    sql杂记
    Spring搭建练习遇到的坑
  • 原文地址:https://www.cnblogs.com/hygeia/p/5129054.html
Copyright © 2011-2022 走看看