flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理
  50 随笔 :: 0 文章 :: 0 评论

分析

难度 易

来源

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

题目

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.

Note:

  • Your returned answers (both index1 and index2) are not zero-based.
  • You may assume that each input would have exactly one solution and you may not use the same element twice.

Example:

Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
解答
 1 package LeetCode;
 2 import java.util.Arrays;
 3 
 4 public class L167_TwoSumII_InputArraySorted {
 5     public int[] twoSum(int[] numbers, int target) {
 6         int front=0,back=numbers.length-1;
 7         while(numbers[front]+numbers[back]!=target){
 8             if(numbers[front]+numbers[back]>target)
 9                 back--;
10             else
11                 front++;
12         }
13         return new int[]{front+1,back+1};//下标计数从1开始
14     }
15     public static void main(String[] args){
16         L167_TwoSumII_InputArraySorted l167=new L167_TwoSumII_InputArraySorted();
17         int[] numbers = {2,7,11,15};
18         int target = 9;
19         int[] result=l167.twoSum(numbers,target);
20    /*     for (int res:result) {
21             System.out.println(res+"\t");
22         }*/
23         System.out.println(Arrays.toString(result));
24     }
25 }

 

 

posted on 2018-11-12 16:20  flowingfog  阅读(54)  评论(0编辑  收藏