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

    Example 1:

    Input: [3,2,1,5,6,4] and k = 2
    Output: 5
    

    Example 2:

    Input: [3,2,3,1,2,4,5,5,6] and k = 4
    Output: 4

    Note: 
    You may assume k is always valid, 1 ≤ k ≤ array's length.

    class Solution {
        public int findKthLargest(int[] nums, int k) {        
            ArrayList<Integer> list = new ArrayList();
            for(int i: nums){
                list.add(i);
            }
            Collections.sort(list);
            Collections.reverse(list);
            return list.get(k-1);
        }
    }

    有很多种解法,最先想到的是存到arraylist里再调用api。

    class Solution {
        public int findKthLargest(int[] nums, int k) {        
            final Queue<Integer> q = new PriorityQueue<>();
    
            for (int x : nums) {
                if (q.size() < k) {
                    q.offer(x);
                } else {
                    final int top = q.peek();
                    if (x > top) {
                        q.poll();
                        q.offer(x);
                    }
                }
            }
            return q.peek();
        }
    }

    priorityqueue:压入随机数,按从小到大输出。设置一个长为k的队列,然后把比最大数和第二大数存入,再peek就是答案,太巧妙了

    class Solution {
        public int findKthLargest(int[] nums, int k) {
            return help(nums, 0, nums.length - 1, nums.length - k);
        }
        public int help(int[] nums, int low, int high, int k) {
            int i = low - 1;
            int pivot = nums[high];
            
            for(int j = low; j < high; j++){
                if(nums[j] < pivot){
                    i++;
                    swap(i, j, nums);
                }
            }
            swap(i+1, high, nums);
            if(i+1 == k) return nums[i+1];
            else if(i + 1 < k) return help(nums, i + 2, high, k);
            else return help(nums, low, i, k);
        }
        public void swap(int i, int j, int[] nums){
            int a = nums[i] + nums[j];
            nums[j] = a - nums[j];
            nums[i] = a - nums[j];
        }
    }

    我这装个逼用quicksort(select)反而更慢了,草,注意是k还是k-1

  • 相关阅读:
    PHP $_SERVER变量
    Buddy system伙伴分配器实现
    Linux iconv使用
    内存管理(memory allocation内存分配)
    内存碎片
    《STL源码剖析》chapter2空间配置器allocator
    Effective C++学习笔记:初始化列表中成员列出的顺序和它们在类中声明的顺序相同
    c++ explicit
    《STL源码剖析》环境配置
    C++ STL的各种实现版本
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11495232.html
Copyright © 2011-2022 走看看