Chinaunix首页 | 论坛 | 博客
  • 博客访问: 224331
  • 博文数量: 41
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 407
  • 用 户 组: 普通用户
  • 注册时间: 2013-06-27 13:42
文章分类

全部博文(41)

文章存档

2016年(1)

2015年(18)

2014年(22)

我的朋友

分类: Java

2015-01-05 15:29:20

问题:

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
题目出处:
思路

    
首先遍历数组生成一个map,然后再遍历一遍,找出解。
     时间复杂度O(n)

代码:

点击(此处)折叠或打开

  1.     public static int[] twoSum(int[] numbers, int target) {
  2.         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
  3.         int ret[] = {-1, -1};
  4.         for (int i = 0; i < numbers.length; i++) {
  5.             map.put(numbers[i], i);
  6.         }
  7.         for (int i = 0; i < numbers.length; i++) {
  8.             if (map.containsKey(target - numbers[i])) {
  9.                 if (map.get(target - numbers[i]) != i) {
  10.                     ret[0] = i + 1;
  11.                     ret[1] = map.get(target - numbers[i]) + 1;
  12.                     break;
  13.                 }
  14.             }
  15.         }
  16.         return ret;
  17.     }


    


阅读(1348) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~