LeetCode:167. Two Sum II - Input array is sorted

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:167. Two Sum II - Input array is sorted相关的知识,希望对你有一定的参考价值。

 1 package Today;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 //LeetCode:167. Two Sum II - Input array is sorted
 7 /*
 8  Given an array of integers that is already sorted in ascending order,
 9  find two numbers such that they add up to a specific target number.
10 
11 The function twoSum should return indices of the two numbers such that they add up to the target, 
12 where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
13 
14 You may assume that each input would have exactly one solution and you may not use the same element twice.
15 
16 Input: numbers={2, 7, 11, 15}, target=9
17 Output: index1=1, index2=2
18  */
19 public class twoSum167 {
20     public static int[] twoSum(int[] numbers, int target) {
21         Map map=new HashMap(); 
22         int index1=0,index2=0;
23         for(int i=0;i<numbers.length;i++){
24             if(map.get(numbers[i])!=null){
25                 index1=(int)map.get(numbers[i])+1;
26                 index2=i+1;
27             }else{
28                 map.put(target-numbers[i], i);
29             }
30         }
31         return new int[]{index1,index2};
32     }
33     //study 不占用多余的空间
34     public static int[] twoSum2(int[] numbers,int target){
35         int left=0,right=numbers.length-1;
36         while(left<right){
37             int sum=numbers[left]+numbers[right];
38             if(sum==target) break;
39             else if(sum>target) right--;
40             else left++;
41         }
42         return new int[]{left+1,right+1};
43         
44             
45     }
46     public static void main(String[] args) {
47         // TODO Auto-generated method stub
48         int[] numbers={2,7,13,15};
49         System.out.println(twoSum(numbers,9)[0]+" and "+twoSum(numbers,9)[1]);
50         System.out.println(twoSum2(numbers,9)[0]+" and "+twoSum2(numbers,9)[1]);
51         int[] numbers2={0,2};
52         System.out.println(twoSum(numbers2,2)[0]+" and "+twoSum(numbers2,2)[1]);
53         System.out.println(twoSum2(numbers2,2)[0]+" and "+twoSum2(numbers2,2)[1]);
54     }
55 
56 }

 

以上是关于LeetCode:167. Two Sum II - Input array is sorted的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode167. Two Sum II - Input array is sorted

LeetCode 167. Two Sum II - Input array is sorted

[LeetCode] 167. Two Sum II - Input array is sorted

LeetCode:167. Two Sum II - Input array is sorted

Leetcode #167. Two Sum II - Input array is sorted

Leetcode167. Two Sum II - Input array is sorted