Two Sum LT1

时间:2022-10-13 15:52:38

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].

Idea: map to store index

Note. 不要忘记加元素进去Map, don't forget o add element to update map.

Time complexity: O(n)

Space complexity: O(n)

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

python

 class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
record = {}
for i in range(len(nums)):
if target - nums[i] in record:
return [record[target-nums[i]], i]
record[nums[i]] = i
return []