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;      }  }  


0 0
原创粉丝点击