167. Two Sum II - Input array is sorted
来源:互联网 发布:decision tree算法 编辑:程序博客网 时间:2024/06/06 02:26
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分别指向数组首尾两端,判断两变量指向的值之和与target的关系:
1. 和与target相等,保存index+1和index+2,返回。
2. 和小于target,index1++;
3. 和大于target,index2–。
如果不满足1,一直遍历到index1>=index2结束循环。
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> result; int index1 = 0; int index2 = numbers.size() - 1; while (index1 < index2) { int sum = numbers[index1] + numbers[index2]; if (sum == target) { result.push_back(index1 + 1); result.push_back(index2 + 1); break; } else if (sum > target) { index2--; } else { index1++; } } return result; }};
0 0
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Two Sum II - Input array is sorted
- Leetcode-167.Two Sum II - Input array is sorted
- [leetcode] 167. Two Sum II - Input array is sorted
- 【leetcode】167. Two Sum II - Input array is sorted
- 【LeetCode】167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- [LeetCode OJ]167. Two Sum II - Input array is sorted
- [leetcode]167. Two Sum II - Input array is sorted
- 167. Two Sum II - Input array is sorted
- 有360重装系统后显示press hot_key to boot previous mbr
- 1.8
- 面向多媒体中心的OpenELEC 7.0稳定Linux发行版本发布
- python-opencv-特征点匹配连线(画线)drawMatches
- pycharm使用bitbucket作代码托管配置20170108
- 167. Two Sum II - Input array is sorted
- WEEX跳坑记
- 动态申请二维数组
- rocketMQ原理与实战
- StopCoroutine协程停止
- $$_javassist_1 cannot be cast to javassist.util.proxy.Proxy
- error: declaration of ‘a’ as multidimensional array must have bounds for all dimensions except ...
- Linux权限设置
- Linux常用命令发布啦!