码迷,mamicode.com
首页 > 其他好文 > 详细

Two Sum II - Input array is sorted(leetcode167) - Solution2

时间:2015-10-13 07:00:36      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

Q: 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

 

Two Sum II - Input array is sorted


public class Solution2{

// O(n) runtime, O(n) space;

// We have two pointers, start and end, 

// firstly, we add start and end, because the array is sorted in ascending order,

//if the sum is smaller than our target, we just increase the start point;

// if the sum is greater than our target, we just decrease the end point,

//keep doing this, until the sum is equal to our target.

  public int[] twoSum(int[] numbers, int target) {

    int i = 0, j = numbers.length - 1;

    while(i < j){
    if(numbers[i] + numbers[j] < target){
      i++;
    } else if(numbers[i] + numbers[j] > target){
      j--;
     } else {
       return new int[] {i+1, j+1};
    }

          }
   throw new IllegalArgumentException("No two sum solution");
  }

}

Two Sum II - Input array is sorted(leetcode167) - Solution2

标签:

原文地址:http://www.cnblogs.com/caomeibaobaoguai/p/4873386.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!