【36】167. Two Sum II - Input array is sorted

167. Two Sum II - Input array is sorted

  • Total Accepted: 52435
  • Total Submissions: 108772
  • Difficulty: Easy
  • Contributors: Admin

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Solution 1: HashMap

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& numbers, int target) {
 4         unordered_map<int, int> hash;
 5         vector<int> res;
 6         for(int i = 0; i < numbers.size(); i++){
 7             if(hash.find(target - numbers[i]) != hash.end()){
 8                 res.push_back(hash[target - numbers[i]] + 1);
 9                 res.push_back(i + 1);
10                 return res;
11             }
12             hash[numbers[i]] = i;
13         }
14         res.push_back(-1);
15         res.push_back(-1);
16         return res;
17     }
18 };

Solution 2: left and right ptr

 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& numbers, int target) {
 4         int left = 0; 
 5         int right = numbers.size() - 1;
 6         vector<int> res;
 7         while(left < right){
 8             int sum = numbers[left] + numbers[right];
 9             if(sum == target){
10                 res.push_back(left + 1);
11                 res.push_back(right + 1);
12                 return res;
13             }else if(sum < target && left < right){
14                 left++;
15             }else if(sum > target && left < right){
16                 right--;
17             }
18         }
19         res.push_back(-1);
20         res.push_back(-1);
21         return res;
22     }
23 };

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2017-02-09 07:16  会咬人的兔子  阅读(217)  评论(0编辑  收藏  举报