两数之和(力扣)
题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
解法一
暴力破解法:
1、第一个循环从数组第一个开始
2、定义一个新的目标值 t2 等于(目标值target减去nums[i])
3、第二个循环从第一个循环当前位置+1开始,防止不必要的重复
4、如果当前第二个循环对应的数等于 t2 ,证明找到结果,返回结果
public class Main {
public static void main(String[] args) {
int[] nums = {-1,-2,-3,-4,-5};
int target = -8;
int[] res = twoSum(nums,target);
System.out.println(res[0]+","+res[1]);
}
public static int[] twoSum(int[] nums, int target) {
int[] res = new int[2];
for(int i=0;i<nums.length;i++){
int t2 = target - nums[i];
for(int j=i+1;j<nums.length;j++){
if(t2==nums[j]) {
res[0] = i;
res[1] = j;
return res;
}
}
}
return res;
}
}
时间复杂度:
空间复杂度:
解法二
哈希表:
map.containsKey(“key”)方法:判断map中是否有key存在,如果有,返回true
public static int[] twoSum2(int[] nums, int target) {
int[] indexs = new int[2];
// 建立k-v ,一一对应的哈希表
HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
if(hash.containsKey(nums[i])){
indexs[0] = i;
indexs[1] = hash.get(nums[i]);
return indexs;
}
// 将数据存入 key为补数 ,value为下标
hash.put(target-nums[i],i);
}
return indexs;
}
时间复杂度:
空间复杂度:
力扣测试结果: