![[leetcode]1. Two Sum两数之和 [leetcode]1. Two Sum两数之和](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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].
Solution1: Brute-force
Lock pointer i, move pointer j to check if nums[j] == target - nums[i].
code:
/* Time Complexity: O(n*n)
Space Complexity: O(1)
*/
class Solution {
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 };
}
}
}
return null;
}
}
Solution2: HashMap
Use a map to record the index of each element and check if target - nums[i] is in the map. if so, we find a pair whose sum is equal to target.
code:
/* Time Complexity: O(n)
Space Complexity: O(n)
*/
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i< nums.length; i++){
if(map.containsKey(target - nums[i])){
return new int[]{i, map.get(target - nums[i])};
}else{
map.put(nums[i], i);
}
}
return null;
}
}