LeetCode——Two Sum

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

题目描述:

给定一个数组,一个数字(Target),寻找数组中两个数字a和b,使得a+b=Target,打印a和b的下标。

题解:

第一反应是如果直接遍历O(N^2)暴力求解肯定TLE,果不其然。

第二反应是用二分查找,O(N*logN)的复杂度应该可以AC,但是我想到一个更简洁的方法,二分就没有测试。

解决方法:

使用HaspMap,遍历numbers数组,将target-numbers[i]放入map,对应的value是i,循环遍历,当发现当前数组元素已经存在于map中,说明和前面的某个元素加起来正好等于target;这时取出map中numbers[i]的value值+1作为第一个数的下标,数组下标i+1作为第二个数的下标。

public int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < numbers.length; i++) {
            int key = numbers[i];
            if (map.containsKey(key)) {//如果map中存在,说明找到了
                res[0] = map.get(key) + 1;
                res[1] = i + 1;
                break;
            } else {
                map.put(target - key, i);//遍历numbers数组,将target-key放入map
            }
        }
        return res;
    }

 

 

posted @ 2014-04-25 22:54  丶Blank  阅读(209)  评论(0编辑  收藏  举报