1.两数相加
1.问题描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
2.问题分析
题目确保了一定有答案,通过遍历数组得到两个相加值为 target 数的下标
2.1 暴力法
暴力枚举所有数的相加结果,由于本题只有一个答案,当满足条件后返回两个下标即可。
时间复杂度: O(n * n )
空间复杂度: O(1)
2.2 哈希法
一次遍历数组,利用HashMap<K,V>来辅助搜索数,K为值,V为下标。
时间复杂度:O(n)
空间复杂度:O(n)
3.代码
3.1 暴力法
for(第一个数还没遍历完){
for(第二个数还没遍历完){
1.相加
2.判断和
3.继续/返回
}
}
public int[] twoSum(int[] nums, int target) {
int[] ans = new int[2];
for(int i = 0; i < nums.length-1; i++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
ans[0] = i;
ans[1] = j;
return ans;
}
}
}
return ans;
}
3.2 哈希法
for(没遍历完){
if(target - num1 存在于map中){
返回
}else{
添加<K,V>键值对
}
}
public int[] twoSum(int[] nums, int target) {
int[] ans = new int[2];
Map<Integer,Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if( map.containsKey(target - nums[i]) ){
ans[0] = map.get(target - nums[i]);
ans[1] = i;
break;
}else{
map.put(nums[i], i);
}
}
return ans;
}
4.运行结果
暴力枚举:
哈希法