【LeetCode】1. Two Sum
Difficulty: Easy
More:【目录】LeetCode Java实现
Description
https://leetcode.com/problems/two-sum/
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 exactlyone 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].
Intuition
1.Brute Force :Time complexity O(n^2); Space complexity O(1); ×
2.Making the use of HashMap to reduce time consumption, (If the complement exists in the array, we need to look up its index. A hash table is the best way to looke up). <nums, index> ==> <key, value>
Solution
public int[] twoSum(int[] nums, int target) { HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i=0; i<nums.length; i++){ if(map.containsKey(target-nums[i])) return new int[]{i,map.get(target-nums[i])}; map.put(nums[i],i); } return null; }
Complexity
Time complexity : O(n)
Space complexity : O(n)
What I've learned
1. How to use HashMap:
* map.put(key, value) ……not "add(K,V)"
* map.containsKey(key)
* map.containsValue(value)
* map.get(key)
* map.remove(key)
* new HashMap<K,V>(); ……two generics ,not one
2. When we need to find something quickly, it's a good way to use HashMap.
3. Be careful when input is [3,2,4] and 6, the output should be [1,2] instead of [0,0] .
More:【目录】LeetCode Java实现