zoukankan      html  css  js  c++  java
  • leetcode 215 数组第k大

    /*
     * @lc app=leetcode.cn id=215 lang=cpp
     *
     * [215] 数组中的第K个最大元素
     */
    
    // @lc code=start
    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            srand(time(0));
            int n = nums.size();
            int x = nums[0];
            int ans = quickSelect(nums,0,n-1,n-k);
            return ans;
        }
        //在[l,r]中找到第index小的数
        int quickSelect(vector<int> &nums,int l,int r,int index) {
    
            rand_pos(nums,l,r);
            int pos = partition(nums,l,r);
            if(pos == index) {
                return nums[pos];
            }
            if(pos > index) {
                return quickSelect(nums,l,pos-1,index);
            }
            else if(pos < index){
                return quickSelect(nums,pos+1,r,index);
            }
            return 0;
        }
        //找到l-r里的一个随机元素,并和nums[r]替换
        //返回大于nums[r]的元素下标
        int rand_pos(vector<int> &nums,int l,int r) {
            int len = r-l+1;
            int rand_pos = l + (rand() % (len));
            swap(nums[rand_pos],nums[r]);
            return 0;
        }
        //把[l,r]里面小于nums[r]的元素放在前面
        //返回大于nums[r]的元素下标
        int partition(vector<int> &nums,int l,int r) {
            int x = nums[r];
            int j = l-1;
            for(int i=l;i<r;i++) {
                if(nums[i] <= x) {
                    swap(nums[++j],nums[i]);
                }
            }
            swap(nums[j+1],nums[r]);
            return j+1;
        }
    };
    // @lc code=end
    
  • 相关阅读:
    软工_个人项目反(shai)思(zhao)
    软工_结对项目总结博客
    软工_个人博客作业3
    软工_个人博客作业2
    软工_个人博客作业1
    软工_个人项目总结博客
    [转]动态规划
    左式堆 优先级队列类模板 归并排序
    1038 约瑟夫环 循环单链表模拟
    链接表 List
  • 原文地址:https://www.cnblogs.com/hh13579/p/15702570.html
Copyright © 2011-2022 走看看