[leetcode] 167. Two Sum II - Input array is sorted

来源:互联网 发布:unity3d转场效果 编辑:程序博客网 时间:2024/05/20 20:43

167. Two Sum II - Input array is sorted
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.

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

题意:
      给定一个整形数组,它已经按升序进行排序,找出两个数字的和等于一个特殊的数字。
      方法应该返回两个数字的索引,index1必须小于index2,请注意,您的答案返回(包括index1和index2)都不是从零开始。
      你可以假定每个输入都有一个解决方案。

方法一:
       思路:
             和[ 1. Two Sum 思想一样,利用<value, index>的映射表。
代码如下:

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {       vector<int> res;       unordered_map<int,int> hash;       for(int i = 0;i<numbers.size();i++){           if(hash.count(target - numbers[i]))           {               res.push_back(hash[target - numbers[i]]+1);               res.push_back(i+1);               //return res;           }           else{               hash[numbers[i]] = i;           }       }       return res;    }};

方法二:
       思路:
             因为这个数组是排序后的增数组,所以可以不用像上面的hash表的方法来返回索引,可以利用指针的思想,提高程序的运行效率,利用一个前向指针pre和一个后向指针tail,先判断两个指针索引所指向的值,求和,小于目标值时pre++,大于时tail–,最后一定找到索引对使其所指整数和等于目标值。

class Solution {public:    vector<int> twoSum(vector<int>& numbers, int target) {       vector<int> res;       int pre = 0;       int tail = numbers.size()-1;       while(pre<tail){            if(numbers[pre]+numbers[tail]==target){                res.push_back(pre+1);                res.push_back(tail+1);                break;            }            else if(numbers[pre]+numbers[tail]<target)                pre++;            else                 tail--;       }       return res;    }};
0 0
原创粉丝点击