CLEAR C++ O(n) (EVERY LINE COMMENTED)


  • 0
    D

    class Solution {
    public:
    vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int,int> map; //create a hash map
    for (int i = 0; i<nums.size(); i++)
    map[nums[i]] = i; //insert vector elements into hashmap in the form where (key,index) becomes (value, index position in nums)
    for (int i = 0; i<nums.size(); i++){
    int comp = target - nums[i]; //calculute the compliment (the number we will search for)
    if (map.find(comp)!=map.end() && map.find(comp)->second != i ){ //if compliment is found & we arent looking at the original num
    vector<int> result = {i, map.find(comp)->second }; //create a vector with the index of the two elements
    return result;
    }
    }
    }
    };


Log in to reply
 

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