My c++ mergesort solution


  • 0
    J
    class Solution {
    public:
        int findKthLargest(vector<int>& nums, int k) {
            mergesort(nums);
            return nums[k-1];
        }
        
        void mergesort(vector<int>& nums){
            if(nums.size()<2)return;
            int mid=nums.size()/2;
            vector<int>v1,v2;
            for(int i=0;i<mid;++i){
                v1.push_back(nums.front());
                nums.erase(nums.begin());
            }
            for(auto i:nums){
                v2.push_back(nums.front());
                nums.erase(nums.begin());
            }
            mergesort(v1);
            mergesort(v2);
            nums=merge(v1,v2);
        }
        
        vector<int> merge(vector<int> &v1,vector<int> &v2){
            vector<int>v;
            while(v1.size()>0&&v2.size()>0){
                if(v1.front()>v2.front()){
                    v.push_back(v1.front());
                    v1.erase(v1.begin());
                }else{
                    v.push_back(v2.front());
                    v2.erase(v2.begin());
                }
            }
            while(v1.size()>0){
                v.push_back(v1.front());
                v1.erase(v1.begin());
            }
            while(v2.size()>0){
                v.push_back(v2.front());
                v2.erase(v2.begin());
            }
            return v;
        }
    };

  • 0

    Am I missing something? What's the point of this?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.