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

Two Sum

时间:2015-02-28 14:21:16      阅读:117      评论: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

 

O(n2)的时间复杂度无法通过,只能用hashmap<K,V>其中K为number,V为number对应下标,遍历数组,若target-number存在于hashmap中,则返回对应下标,若不存在,则将number和其对应下标存入hashmap中。代码如下:

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
         int[] re = new int[2];
         Map<Integer,Integer> map = new HashMap<Integer,Integer>();
         int size = numbers.length;
         for(int i=0;i<size;i++) {
             int tmp = target-numbers[i];
             if(!map.containsKey(tmp)) {
                map.put(numbers[i],i);
             }
             else {
                 int index = map.get(tmp);
                 re[0] = (i<index?i:index)+1;
                 re[1] = (i>index?i:index)+1;
             }
         }
         return re;
    }
}

 

Two Sum

标签:

原文地址:http://www.cnblogs.com/mrpod2g/p/4305263.html

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