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

leetcode001:TwoSum(5.5)

时间:2015-05-05 23:46:09      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

Given an array of integers, 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

给出一组整数,找到两个数A和B,使得A+B=目标数。输出这两个数的index,从小到大,并且注意不要从0开始计数,如下所示。你可以假设有且只有一个解。

技术分享
 1 public static int[] twoSum(int[] numbers, int target) {
 2         int[] res = new int[2];
 3         HashMap<Integer,Integer> nums = new HashMap<Integer,Integer>();
 4         for(int i=0;i<numbers.length;i++){
 5             Integer a = nums.get(numbers[i]);
 6             if(a == null){
 7                 nums.put(numbers[i], i);
 8             }
 9             a = nums.get(target - numbers[i]);
10             if(a!=null&&a<i){
11                 //说明找到解了
12                 res[0] = a+1;
13                 res[1] = i+1;
14                 break;
15             }else{
16                 res[0] = -1;
17                 res[1] = -1;
18             }
19         }
20         return res;
21         
22      }
View Code

 

leetcode001:TwoSum(5.5)

标签:

原文地址:http://www.cnblogs.com/liyuhui21310122/p/4480612.html

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