Leetcode-Two Sum(java)

1 Description(描述)

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].
举例:
给定一个数组nums=[2, 7, 11, 15],特定值为target = 9,因为nums[0] + nums[1] = 2 + 7 = 9,因此返回的是[0, 1]。

2 Solution(解决方案)

Approach 1: Brute Force(方法一:蛮力)
The brute force approach is simple. Loop through each element x and find if there is another value that equals to target - x.
蛮力方法很简单。通过循环遍历每个元素 x 并且寻找是否存在另一个等于特定值target - x 的值。

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[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

Complexity Analysis:(复杂度分析)

1 Time complexity : O(n2) For each element, we try to find its complement by looping through the rest of array which takes O(n) time. Therefore, the time complexity is O(n2).
1 时间复杂度:O(n2)。对于每个元素,我们都试图通过遍历数组中的其余元素来找他的另一半加数,这花费了O(n)的时间。因此,时间复杂度为O(n2)。

2 Space complexity : O(1).
2 空间复杂度: O(1)。

Approach 2: Two-pass Hash Table(使用两次哈希表)
To improve our run time complexity, we need a more efficient way to check if the complement exists in the array. If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element in the array to its index? A hash table.
为了优化我们的时间复杂度,我们需要一个更有效的方法来检查是否在数组中有这样的加数存在。如果存在,我们需要寻找他的索引。保持数组中每个元素与其索引关系映射的最好的方法是什么?利用一个哈希表。

We reduce the look up time from O(n) to O(1) by trading space for speed. A hash table is built exactly for this purpose, it supports fast look up in near constant time. I say “near” because if a collision occurred, a look up could degenerate to O(n) time. But look up in hash table should be amortized O(1) time as long as the hash function was chosen carefully.
我们通过牺牲空间来换取速度的方式,将查找时间从O(n) 减少到了 O(1)。哈希表就是为了这个目标才被建立的,他支持接近常量时间内的快速查找。我说的“接近”是因为如果发生了检测碰撞,查找时间将会退化成 O(n) 。但是只要我们谨慎地选择哈希方法,在哈希表中查找的时间应该平均为O(1)。

A simple implementation uses two iterations. In the first iteration, we add each element’s value and its index to the table. Then, in the second iteration we check if each element’s complement (target - nums[i]) exists in the table. Beware that the complement must not be nums[i] itself!
一个简单的实现通过两次迭代。第一次迭代,我们将每个元素的值以及索引放入哈希表中。第二次迭代,我们检查每个元素对应的加数(target - nums[i])是否存在于哈希表中。要注意的是,这个加数一定不能是nums[i]本身!

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

Complexity Analysis:(复杂度分析)
1 Time complexity : O(n). We traverse the list containing n elements exactly twice. Since the hash table reduces the look up time to O(1), the time complexity is O(n).
1 时间复杂度:O(n)。我们两次遍历包含 n 个元素的列表。但由于哈希表将查找的时间减少到了O(1),所以时间复杂度为O(n)。

2 Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores exactly n elements.
2 空间复杂度:O(n)。所需的额外空间取决于哈希表中存储的项的个数,哈希表恰好存储了n个元素。

Approach 3: One-pass Hash Table(仅适用一次哈希表)
It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back to check if current element’s complement already exists in the table. If it exists, we have found a solution and return immediately.
当我们迭代元素并将其插入到表中时,我们还会回头检查当前元素的加数是否已经存在于表中。如果它存在,我们已经找到解决方法并立即返回。

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

Complexity Analysis:(复杂度分析)
1 Time complexity : O(n). We traverse the list containing n elements only once. Each look up in the table costs only O(1) time.
1 时间复杂度:O(n)。我们仅遍历一次包含 n 个元素的列表。每次在哈希表中的查找仅花费O(1)的时间。

2 Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores at most n elements.
2 空间复杂度:O(n)。所需的额外空间取决于哈希表中存储的项的个数,哈希表恰好存储了n个元素。

注:内容均来源于leetcode。

猜你喜欢

转载自blog.csdn.net/qq_38003892/article/details/84711906
今日推荐