Article Directory
1. Description
Given an integer array nums and a target value target, please find the two integers whose sum is the target value in the array and return their array subscripts.
You can assume that each input will only correspond to one answer. However, the same element in the array cannot be used twice.
2. Example
Given nums = [2, 7, 11, 15], target = 9
because nums[ 0 ] + nums[ 1 ] = 2 + 7 = 9
so return [0, 1]
3. Analysis
Goal: Find two numbers from the array so that their sum is equal to a given value.
Two limitations are given in the title. The first point is that for a given value, there will only be one situation in the array that makes the sum of the two numbers meet the condition; the second point is that the same element in the array cannot be used twice.
3.1. Brute force search
For all the values in the array, perform pairwise matching, and their sum is equal to the given value, and these two numbers are found.
Two levels of traversal are required, and each level of traversal searches for a number; when their sum is equal to a given value, the search stops.
Time complexity: O (n 2) O(n^2) in the worst caseO ( n2)。
3.2. Dictionary matching
Knowing the target value, the complement of a number can be determined.
For example, now it is required that the sum of 2 numbers is 9, one of which is 1, and what is the other?
The other number is 8 (9-1), which is num2 = target-num1.
We can take advantage of this property.
We need to visit the array once, set the currently visited array element as nums[i], and look up whether nums[i] already exists (key) in a dictionary.
If it does not exist, use (target-nums[i]) as the key (key) of the dictionary, and insert the subscript i as the value (value) of the dictionary;
if it already exists, specify (target-nums[i] ) Must exist in the array nums and have been visited, its subscript can be obtained from the dictionary.
In this way, these two numbers can be obtained with only one traversal.
Time complexity: O (n) O(n) in the worst caseO ( n )。
4. Code
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
out:
for(int i = 0; i < nums.length; ++i)
{
for(int j = i + 1; j < nums.length; ++j)
{
if(nums[i] + nums[j] == target)
{
indices[0] = i;
indices[1] = j;
break out;
}
}
}
return indices;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
Map<Integer, Integer> dict = new HashMap<>();
for(int i = 0; i < nums.length; ++i)
{
if(dict.containsKey(nums[i]))
{
indices[0] = dict.get(nums[i]);
indices[1] = i;
break;
}
else
{
dict.put(target - nums[i], i);
}
}
return indices;
}
}
5. Verification
6. Source
- LeetCode 1. Sum of two numbers
Source: LeetCode
Link: https://leetcode-cn.com/problems/two-sum The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.