【LeetCode 刷题】1. Two Sum

in 编程 with 0 comment

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, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

第一次尝试,使用双循环,效率肯定是不尽人意的,不过考虑到是第一次刷 LeetCode 有情可原

Runtime: 90 ms
Memory Usage: 40.2 MB

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) return new int[] { i, j };
            }
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

第二次尝试,看了一下大佬们的思路,用的是 HashMap。

Runtime: 1 ms
Memory Usage: 39.6 MB

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int diff = target - nums[i];
            if (map.containsKey(diff)) {
                return new int[]{map.get(diff), i};
            }
            map.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
}
Responses