Two Sum LT1

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)

 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         Map<Integer, Integer> record = new HashMap<>();
 4         for(int i = 0; i < nums.length; ++i) {
 5             Integer index = record.get(target - nums[i]);
 6             if(index != null) {
 7                 return new int[] {index, i};
 8             }
 9             record.put(nums[i], i);
10         }
11         
12         return new int[0];
13     }
14 }

python

1 class Solution:
2     def twoSum(self, nums: List[int], target: int) -> List[int]:
3         record = {}
4         for i in range(len(nums)):
5             if target - nums[i] in record:
6                 return [record[target-nums[i]], i]
7             record[nums[i]] = i
8         return []

posted on 2019-03-27 06:03  一直走在路上  阅读(124)  评论(0编辑  收藏  举报

导航