leetcode--Two Sum II - Input array is sorted
来源:互联网 发布:手机转区软件 编辑:程序博客网 时间:2024/05/16 14:18
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
题意:给你一个升序排列的数组和一个target,在数组中找出两个和为target的整数。
返回这两个整数的index,并且要求index1小于index2
注意,index是基于1开始的,也就是说数组的第一个index是1,而不是0
分类:数组
解法1:这个题目比Two Sum http://blog.csdn.net/crazy__chen/article/details/45441671
还要简单,因为数组已经排好序了,用两个指针分别从头尾开始找就可以了。
如果头尾和大于target,说明尾太大,小于target说明头太小。
根据大小移动指针即可。
public class Solution { public int[] twoSum(int[] numbers, int target) { if(numbers==null || numbers.length < 1) return null; int i=0, j=numbers.length-1; while(i<j) { int x = numbers[i] + numbers[j]; if(x<target) { ++i; } else if(x>target) { –j; } else { return new int[]{i+1, j+1}; } } return null; } }
- 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
- select下拉框可输入值
- 新的Android databinding与android-apt plugin冲突
- Mac 10.10 配置tomcat 服务器
- codeforces 567D One-Dimensional Battle Ships (set)
- Oracle创建表空间,用户,分配权限
- leetcode--Two Sum II - Input array is sorted
- Hdu 2015 Multi-University Training Contest6
- eclipse从数据库逆向生成Hibernate实体类
- FileToData与DataToFile(优化版,txt为原始文件2倍大小)
- 一次「Too many open files」故障
- Codeforces 567 E. President and Roads
- Symmetric Tree
- Java动态代理实现(简单AOP实现)
- ViewPager findViewById错误NullPointerException