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

  • 相关阅读:
    day77 vue对象提供的属性功能
    day76 作业
    day76 vue框架入门
    day75 bbs项目☞后台管理+修改头像
    day74 bbs项目☞点赞与评论
    day73 bbs项目☞基本功能实现
    day72 bbs项目☞登录注册
    练习题00
    雇1个人工作7天,你有1根金条可以分成7份,只能切2刀,如何保证每天都得到1份金条
    Python正课143 —— DRF 进阶4 权限、频率、过滤、排序
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11495232.html
Copyright © 2011-2022 走看看