LeetCode: Two Sum II - Input array is sorted
来源:互联网 发布:数据泄露防护系统 编辑:程序博客网 时间:2024/06/07 03:43
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
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { int len = numbers.size(); int idx1 = 0, idx2 = len - 1; while(idx1 < idx2) { int tmp = numbers[idx1] + numbers[idx2]; if (tmp < target) idx1++; else if (tmp > target) idx2--; else break; } vector<int> res; res.push_back(idx1 + 1); res.push_back(idx2 + 1); return res; }};
1 0
- leetcode 167: Two Sum II - Input array is sorted
- Leetcode NO.167 Two Sum II - Input array is sorted
- LeetCode-Two Sum II - Input array is sorted
- [Leetcode]Two Sum II - Input array is sorted
- leetcode--Two Sum II - Input array is sorted
- LeetCode 题解(274) : Two Sum II - Input array is sorted
- [LeetCode] 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 Two Sum II – Input array is sorted (Java)
- [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 C++
- [leetcode]167. Two Sum II - Input array is sorted
- 【Leetcode】Two Sum II - Input array is sorted
- 我做草根站长的这两年,靠互联网赚钱到底难不难
- 程序员进阶的10大黄金法则
- bzoj 1832: [AHOI2008]聚会 lca
- EXTJS4.0 3种和后台交互数据的方法
- 87. Scramble String
- LeetCode: Two Sum II - Input array is sorted
- 文字记忆
- NYOJ17-LIS优化
- 继承
- 全角转半角笔记
- 在PHP中使用Mysqli操作数据库
- JAVA 网络编程 Socket 详细说明,实现客户端和服务端相互推送消息
- MyBatis学习总结(八)——Mybatis3.x与Spring4.x整合
- eclipse设置默认编码