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

167. Two Sum II - Input array is sorted

时间:2017-02-20 13:27:26      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:order   color   cti   ems   get   ase   problems   span   search   

题目:

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

链接: http://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

2/19/2017, Java

没有想到用binary search的方法,就是两个指针每次走1步的算法。

 1 public class Solution {
 2     public int[] twoSum(int[] numbers, int target) {
 3         int i = 0;
 4         int j = numbers.length - 1;
 5         int sum = 0;
 6         int[] ret = new int[2];
 7         
 8         while (i < j && i >= 0 && j <= numbers.length - 1) {
 9             sum = numbers[i] + numbers[j];
10             if (sum > target) j--;
11             else if (sum < target) i++;
12             else {
13                 ret[0] = i + 1;
14                 ret[1] = j + 1;
15                 return ret;
16             }
17         }
18         return ret;
19     }
20 }

 

167. Two Sum II - Input array is sorted

标签:order   color   cti   ems   get   ase   problems   span   search   

原文地址:http://www.cnblogs.com/panini/p/6418878.html

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