1. 两数之和 Java解法

这题属于Leetcode的签到题,基本上每个人一进来就是这题。
用哈希思想来做就是最好的解答。
如果一个target - num[i] 存在那么就返回那个数字对应的下标和当前元素的下标。

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    int[] res = new int[2];
    for (int i = 0, len = nums.length; i < len; ++i) {
        if (map.containsKey(target - nums[i])) {
            return new int[]{map.get(target - nums[i]), i};
        } else {
            map.put(nums[i], i);
        }
    }
    return res;
}

猜你喜欢

转载自www.cnblogs.com/jamesmarva/p/11210433.html