分享

leetcode 167: Two Sum II

 雪柳花明 2016-10-20

Two Sum II - Input array is sorted

 Total Accepted: 441 Total Submissions: 1017

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

[分析]

greedy algorithm, 两头pointer 向中间移动.

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class Solution {  
  2.     public int[] twoSum(int[] numbers, int target) {  
  3.         if(numbers==null || numbers.length < 1return null;  
  4.         int i=0, j=numbers.length-1;  
  5.           
  6.         while(i<j) {  
  7.             int x = numbers[i] + numbers[j];  
  8.             if(x<target) {  
  9.                 ++i;  
  10.             } else if(x>target) {  
  11.                 --j;  
  12.             } else {  
  13.                 return new int[]{i+1, j+1};  
  14.             }  
  15.         }  
  16.         return null;  
  17.     }  
  18. }  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多