Merge Sorted Array

mail@pastecode.io avatar
unknown
c_cpp
23 days ago
1.0 kB
3
Indexable
Never
class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        std::unordered_map<int,int> numCounts;
        bool passedZeros=false;
        for(int i=0;i<m;i++)
        {
            if(passedZeros && nums1[i]==0)
                break;
            if(numCounts.count(nums1[i]))
                numCounts[nums1[i]]=numCounts[nums1[i]]+1;
            else
                numCounts[nums1[i]]=1;
            if(nums1[i]>0)
                passedZeros=true;
        }
        for(int i=0;i<n;i++)
        {
            if(numCounts.count(nums2[i]))
                numCounts[nums2[i]]=numCounts[nums2[i]]+1;
            else
                numCounts[nums2[i]]=1;
        }

        int i=0;
        for(auto it:numCounts)
        {
            int amount=it.second;
            for(int y=0;y<amount;y++)
            {
                nums1[i]=it.first;
                ++i;
            }
        }
        std::sort(nums1.begin(),nums1.end());
    }

};
Leave a Comment