Share my C++ solution,easy to understand


  • 8
    V
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            int i = 0, n = nums.size();
            unordered_map<int, int> m;
            vector<int> ret;
            
            for (i = 0; i < n; ++i)
            {
                if (m.find(target - nums[i]) != m.end())
                {
                    ret.push_back(m[target - nums[i]]);
                    ret.push_back(i);
                    break;
                }
                m[nums[i]] = i;
            }
            
            return ret;
        }
    };

Log in to reply
 

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