Untitled

mail@pastecode.io avatar
unknown
plain_text
19 days ago
992 B
4
Indexable
Never
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_multimap<int, int> mp;
        vector<int> ans(2);
        for (int i = 0; i < nums.size(); i++)
        {
            mp.insert({nums[i], i});
        }

        for (auto& x: mp)
        {
            int newNum = target - x.first;
            auto res = mp.count(newNum);
            if (res < 1)
                continue;

            if (newNum == x.first && res > 1)
            {
                auto range = mp.equal_range(newNum);
                auto firstEle = range.first;
                ans[0] = firstEle->second;
                firstEle++;
                ans[1] = firstEle->second;
                break;
            }
            else if(newNum != x.first)
            {  
                ans[0] = x.second;
                ans[1] = mp.find(newNum)->second;

                break;
            }   
        }

        return ans;
    }
};
Leave a Comment