leetcode-1-Two Sum
1. 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.
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.
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 int max = nums.size(); 5 vector<int> twoSum = { max, max }; 6 int i, j; 7 for (i = 0; i < nums.size(); i++) 8 { 9 for (j = i + 1; j < nums.size(); j++) 10 { 11 if ((nums[j] + nums[i]) == target) 12 {14 if ((twoSum[0] + twoSum[1]) >(i + j)) 15 { 16 twoSum[0] = i; 17 twoSum[1] = j; 18 } 19 } 20 } 21 } 22 return twoSum; 23 } 24 };//1.注意twoSum和要最小 2.vector.size()
注意:
1.twoSum有多个答案时和要取最小
2.vector.size()