1. Two Sum
Total Accepted: 238787 Total Submissions: 999694 Difficulty: Easy
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
Subscribe to see which companies asked this question
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> v = nums; 5 vector<int> w; 6 sort(nums.begin(), nums.end()); 7 int i = 0, j = nums.size() - 1; 8 while (i < j){ 9 if (nums[i] + nums[j] == target){ 10 for (int m = 0; m < v.size(); m++){ 11 if (v[m] == nums[i]){ 12 w.push_back(m); 13 continue; 14 } 15 if (v[m] == nums[j]){ 16 w.push_back(m); 17 } 18 } 19 sort(w.begin(), w.end()); 20 break; 21 } 22 else if (nums[i] + nums[j] < target){ 23 i++; 24 } 25 else{ 26 j--; 27 } 28 } 29 return w; 30 } 31 };
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> v; 5 map<int, int> m; 6 map<int, int>::iterator iter; 7 for (int i = 0; i < nums.size(); i++){ 8 int complement = target - nums[i]; 9 iter = m.find(complement); 10 if(iter != m.end()) 11 { 12 v.push_back(m[complement]); 13 v.push_back(i); 14 break; 15 } 16 m[nums[i]] = i; 17 } 18 return v; 19 } 20 };