首页 > 其他 > 详细

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

时间:2015-10-13 06:58:28      阅读:673      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!