leetcode 1. Two Sum
1. Two Sum
My SubmissionsTotal Accepted: 193086 Total Submissions: 899528 Difficulty: Medium
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
Show Similar Problems
最简单的思路,两层for循环,640ms
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 int i,j; 5 vector<int> ans; 6 int n = nums.size(); 7 int sum; 8 for(i = 0; i < n ;i++){ 9 for(j = i + 1;j < n ;j++){ 10 sum = nums[i] + nums[j]; 11 if(sum == target){ 12 ans.push_back(i); 13 ans.push_back(j); 14 return ans; 15 } 16 } 17 } 18 } 19 };
考虑到题目说解是唯一的,那么用hash可求得(32ms):
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 int i,j; 5 vector<int> ans; 6 map<int,int> mp; 7 int n = nums.size(); 8 for(i = 0;i < n;i++){ 9 mp[ nums[i] ] = i + 1; 10 } 11 for(i = 0;i < n;i++){ 12 int left = target - nums[i]; 13 j = mp[ left ]; 14 if(j >= 1 && j != i + 1){ 15 ans.push_back(i); 16 ans.push_back(j - 1); 17 return ans; 18 } 19 } 20 } 21 };