Tuesday, 4 October 2016

Two Sum (LeetCode)

Problem: Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int, int> hashTable;
        vector<int> indices;
        for(int i=0;i<nums.size();i++)
        if(hashTable[target-nums[i]]!=0)
        {
            
            indices.push_back(hashTable[target-nums[i]]-1);
            indices.push_back(i);
           // cout<<indices[0]<< " " <<indices[1]<<endl;
            return indices;
        }
        else hashTable[nums[i]]=i+1;
    return indices;
    }
};

No comments:

Post a Comment