167. Two Sum II - Input array is sorted 难度:medium
来源:互联网 发布:知达常青藤中学校费用 编辑:程序博客网 时间:2024/05/17 04:27
题目:
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=9Output: index1=1, index2=2
思路:
定义两个指针i,j分别指向数组的开头和结尾,当i,j所指元素的和大于所给元素时,j减一,当i,j所指元素的和小于所给元素时i加一,指导i,j所指元素的和等于所给元素。
程序:
class Solution {public: vector<int> twoSum(vector<int>& numbers, int target) { vector<int> res; int i = 0; int j = numbers.size() - 1; while(1) { int x = numbers[i] + numbers[j]; if(x == target) break; else if(x > target) j--; else i++; } res.push_back(i + 1); res.push_back(j + 1); return res; }};
0 0
- 167. Two Sum II - Input array is sorted 难度:medium
- 167. Two Sum II - Input array is sorted [medium] (Python)
- 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 (Medium) (cpp)
- 167.leetcode Two Sum II - Input array is sorted(medium)[两数求和固定值]
- 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
- 单例模式 接口回调 异常
- IplImage结构体
- Ubuntu下安装hive,并配置mysql作为元数据库
- TBSchedule原理与实践
- UVA12333--Revenge of Fibonacci
- 167. Two Sum II - Input array is sorted 难度:medium
- C++关于堆上与栈上分配对象
- leetcode交换相邻的两个节点的值
- 用Python做投资-关于term spread
- 内存初始化(上)
- Laxcus大数据管理系统单机集群版
- Android中的调色板功能的实现
- 71. Simplify Path
- emacs注释快捷键