Accepted C++ 3ms


  • 0
    I
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int> res;
            unordered_map<int,int> num_1;
            unordered_map<int,int> num_2;
            for(int i=0;i<nums.size();i++) {
                if(num_1.find(nums[i])==num_1.end()){
                    num_1[nums[i]]=i;
                }else{
                    num_2[nums[i]]=i;
                }
            }
            for(int i=0;i<nums.size();i++) 
                if(num_1.find(target-nums[i])!=num_1.end()){
                    if(nums[i]==target-nums[i]){
                        if(num_2.find(target-nums[i])!=num_2.end()){
                            res.push_back(num_1[nums[i]]);
                            res.push_back(num_2[target-nums[i]]);
                            return res;
                        } else
                            continue;
                    } else{
                        res.push_back(num_1[nums[i]]);
                        res.push_back(num_1[target-nums[i]]);
                    
                        return res;
                    }
                }
        }
    };
    

Log in to reply
 

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