leetCode刷题归纳-Divide and Conquer(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.

非分治算法


利用STL map自动排序的特点,对hash表做一个遍历:

 ---------------自己想的指针的方法,AC但是没有用到分治的思想-----
    int findKthLargest(vector<int>& nums, int k) {
        if(nums.empty()) return 0;
        map<int,int> m;
        for(int x:nums)
            m[x]++;
        map<int,int>::iterator p=m.end();
        int count=0;
        while(count<k){
            --p;
            count+=p->second;
        }
        return p->first;
    }

分治算法


这个题目的分治解法中加入了快排的思想,下面是分析的思路:

  • 首先是对于quicksort的理解,这里有一篇很好的博文:
    http://blog.csdn.net/morewindows/article/details/6684558

  • 为什么要用quicksort,因为每一步选取index的过程和快排的一步循环很像

  • 不同点在哪?因为题目的要求是找出排在第k个的元素,所以每次的merge就是对一部分进行处理,舍弃掉不包括索引是k-1元素的部分进行递归操作:

//类似于快排 将第一个元素在排序后序列中的索引找出来,然后返回其索引
//这样做实际上就是随机选择了一个第?大的元素,然后比较?与k-1的大小关系再判定下一步操作区域
  int partition(vector<int>&nums,int left,int right){
        int l=left+1,r=right,pivot=nums[left];
        while(l<=r){
            if(nums[l]<pivot&&nums[r]>pivot) swap(nums[l++],nums[r--]);
            if(nums[l]>=pivot) l++;
            if(nums[r]<=pivot) r--;
        }
        swap(nums[left],nums[r]);
        return r;
    }
    int findKthLargest(vector<int>& nums, int k) {
        //按照专题要求下面是分治的解法
        int left=0,right=nums.size()-1;
        while(true){
            int pos=partition(nums,left,right);
            if(pos==k-1)  return nums[pos];
            else if(pos>k-1) right=pos-1;
            else left=pos+1;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值