[LeetCode] No.1 Two Sum

链接:https://leetcode.com/problems/two-sum/submissions/
原题:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

**UPDATE (2016/2/13):
**The return format had been changed to zero-based indices. Please read the above updated description carefully.

Subscribe to see which companies asked this question

分析:
这道题,要求是给一个数组,给一个数字,返回两个数组元素之和等于这个数字的位置,而且说了,假设一个数组只有一个解法。
首先想到暴力破解,但是暴力破解很显然不够LeetCode的B格
在这题里面用到了Map

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
            Map> maps = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
           if(maps.get(nums[i])!=null) {
                maps.get(nums[i]).add(i);
            } else {
                List list = new ArrayList<>();
                list.add(i);
                maps.put(nums[i], list);
            }
        }
        for (int key : maps.keySet()) {
            int tmp = target - key;
            if(tmp == key && maps.get(key).toArray().length>1) {
                result[0] = (int) maps.get(key).toArray()[0];
                result[1] = (int) maps.get(key).toArray()[1];
                break;
            }
            if (maps.get(tmp) != null) {
                result[0] = maps.get(key).get(0);
                result[1] = maps.get(tmp).get(0);
                break;
            }
        }
        return result;
    }
}

这是一开始的方法

public class Solution {
    public int[] twoSum(int[] nums, int target) {
         HashMap map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.get(nums[i]) != null) {
                int[] result = {map.get(nums[i]) , i};
                return result;
            }
            map.put(target - nums[i], i);
        }

        int[] result = {};
        return result;
    }
}

后来改进的方法。

第一种方法是我自己的实现,第二种方法是看九章的实现。 在ac的过程中,第一种要耗时12ms, 第二种耗时6ms,仔细阅读一下,确实发现是我太愚钝了~

你可能感兴趣的:([LeetCode] No.1 Two Sum)