167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]
来源:互联网 发布:马云说的阿里健康 编辑:程序博客网 时间:2024/06/06 12:52
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.
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int n = numbers.size(); vector<int> result; if(n<=1) return result; int start = 0,end = n-1; while(start<end) { if(numbers[start]+numbers[end]<target) { ++start; }else if(numbers[start]+numbers[end]>target) { --end; }else { result.push_back(start+1); result.push_back(end+1); break; } } return result; }};
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
与2sum的解决方法相似,从两端向中间遍历,当得到第一个和为target的break,如果比target大则末端指针减1,如果比target小则前端指针加1.
0 0
- 167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]
- LeetCode 167. Two Sum II - Input array is sorted(两数和)
- 167. Two Sum II - Input array is sorted [medium] (Python)
- 167. Two Sum II - Input array is sorted 难度:medium
- Leetcode 167. Two Sum II - Input array is sorted (Medium) (cpp)
- Medium 167题 Two Sum II - Input array is sorted
- [Medium] 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
- [LeetCode OJ]167. Two Sum II - Input array is sorted
- [leetcode]167. Two Sum II - Input array is sorted
- leetcode-java-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
- [LeetCode] 167. Two Sum II - Input array is sorted
- android多级树形列表
- js对象
- Java向前引用和静态初始化
- Android开发 点击在本地选择换图片(头像)并且保存,实例总结。
- 银行卡四元素实名认证
- 167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]
- 是时候来了解android7了:多窗口支持
- 跨域ajax
- SSRS 报表日志查看器
- 第一行代码:AlertDialog
- 求区间内最大值问题(线段树)(hdu 1754)
- Facial landmark detection by deep multi-task learning
- 【播放器】关于 sewisePlayer HLS视频播放器的二次开发(二)
- 英语的几个基本语法概念