LeetCode: 1. Two Sum
question:
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.
中文:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
思路&总结:
- 首先想到-----可以使用暴力法,依次遍历数组内的元素,循环内再遍历其余剩下的元素,如果符合条件nums[j]==target-nums[i],就返回两个元素的下标。
- 改进-----------利用哈希映射 降低时间复杂度,遍历数组 nums,i 为当前下标,每个值都判断map中是否存在 target-nums[i] 的 key 值
如果存在则找到了两个值,如果不存在则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止
源代码:
public class Two_Sum {
//暴力遍历法 时间复杂度:o(n^2) 空间复杂度:o(1)
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 };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
public class Two_Sum {
//哈希映射 时间复杂度:o(n) 空间复杂度:o(n)
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[]{map.get(target - nums[i]), i};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}