zoukankan      html  css  js  c++  java
  • LN : leetcode 215 Kth Largest Element in an Array

    lc 215 Kth Largest Element in an Array


    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.
    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.

    multiset Accepted

    投机取巧的方法,利用stl中multiset的特性,自动实现从小到大的排序,并且允许有相同元素的存在,但是要注意,multiset不能用下标获取元素,所以需删除之前不必要的元素,用*ans.begin()的方法获取首元素。

    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
           multiset<int> ans;
            for (auto i : nums) {
                ans.insert(i);
            }
            while (ans.size() > k)  ans.erase(ans.begin());
            return *ans.begin();
        }
    };
    

    分治 Accepted

    类似于快排的原理,其中也蕴含了分治的思想。

    class Solution {
    public:
        void swap(vector<int>& nums, int i, int j) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        
        int findKthLargest(vector<int>& nums, int k) {
            int n = nums.size();
            int p = quick(nums, 0, n-1, n-k+1);
            return nums[p];
        }
        
        int quick(vector<int>& a, int low, int high, int k) {
            int i = low, j = high, pivot = a[high];
            while (i < j) {
                if (a[i++] > pivot) swap(a, --i, --j);
            }
            swap(a, i, high);
            int m = i - low + 1;
            if (m == k)     return i;
            else if (m > k) return quick(a, low, i - 1, k);
            else            return quick(a, i + 1, high, k - m);
        }
    };
    

    将递归转化成递推

    思想和上面的方法是一样的,但是将递归转化成递推。

    void swap(vector<int>& nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
    
    int findKthLargest(vector<int>& nums, int k) {
        k = nums.size() - k;
        int l = 0, r = nums.size() - 1;
        while (l <= r) {
            int i = l;
            for (int j = l + 1; j <= r; j++)
                if (nums[j] < nums[l]) swap(nums, j, ++i);
            swap(nums, l, i);
    
            if (k < i) r = i - 1;
            else if (k > i) l = i + 1;
            else return nums[i];
        }
        return -1;
    }
    
  • 相关阅读:
    myeclipse6.5设置智能提示
    web项目无法编译
    Duplicate property mapping of .....
    SSH常见面试题
    简易计算器JS方式实现
    js中两个感叹号的作用
    Pro Javascript Design Patterns勘误Errata汇总(持续更新中)
    Javascript简写条件语句
    js中值得推荐的Memoization
    使用au3脚本编写自动登录126邮箱
  • 原文地址:https://www.cnblogs.com/renleimlj/p/8046762.html
Copyright © 2011-2022 走看看