[leetcode]1. Two Sum两数之和

时间:2023-03-09 01:32:46
[leetcode]1. Two Sum两数之和

Given an array of integers, return indices  [leetcode]1. Two Sum两数之和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].

[leetcode]1. Two Sum两数之和

[leetcode]1. Two Sum两数之和

[leetcode]1. Two Sum两数之和

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.

[leetcode]1. Two Sum两数之和

[leetcode]1. Two Sum两数之和

[leetcode]1. Two Sum两数之和

[leetcode]1. Two Sum两数之和

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;
}
}