Two Sum II - Input array is sorted
来源:互联网 发布:农业供给侧 知乎 编辑:程序博客网 时间:2024/05/21 22:06
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
Have you met this question in a real interview?
思路:双指针;
public class Solution { public int[] twoSum(int[] numbers, int target) { int[] res = new int[]{-1,-1}; int start = 0; int end = numbers.length-1; while(start<end){ int sum = numbers[start]+numbers[end]; if(sum == target){ res[0] = start+1; res[1] = end+1; return res; }else if(sum >target){ end--; }else{ // sum<target start++; } } return res; }}
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
- Leetcode167 - Two Sum II - Input array is sorted(two pointers)
- 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
- 167 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
- [LeetCode167]Two Sum II - Input array is sorted
- win7的hosts文件不能修改
- 关于Netflix Prize的总结
- android 中java包功能描述
- SSH Secure Shell的应用
- 一个图片
- Two Sum II - Input array is sorted
- Qualcomm平台camera调试移植入门
- Elasticsearch-索引优化篇1
- Android ListView item 点击背景不变色
- IIC和SPI总线
- LeetCode--Reverse Integer
- live555单线程原理
- Binary Tree Inorder Traversal
- web.xml配置文件的加载顺序