top of page

Leetcod#1: Two sum

  • Writer: Ann Liu
    Ann Liu
  • Aug 29, 2019
  • 1 min read

(improved solution)

language: C++

key idea: STL map

map use:

1. define -- map<key, value>

2. find -- map.find(key)


code:

class Solution {

public:

vector<int> twoSum(vector<int>& nums, int target) {

vector<int> ans;

map<int,int> table;

for(int i=0; i<nums.size();i++){

int res = target - nums[i];

map<int,int>::iterator it = table.find(res);

if(it != table.end()){

return vector<int>({it->second,i});

}

table[nums[i]] = i;

}

return ans;

}

};


Time complexity: O(n) (hash table search time:O(1))

Space complexity: O(n) - nums stored in the hash table


Comments


Post: Blog2_Post

©2018 by Something or Nothing. Proudly created with Wix.com

bottom of page