首先两层for循环的是时间复杂度是 On^2, 在此就不说了.
所以我们这边要优化时间复杂度. 此时间复杂度为On.
1. 获取 和 - 当前值 = 差; 我们查询差值是在之前存在.
2. 如何判断差是否存在? 在次我们用的map 存储之前的值. key 为数组值,value 为下标.
/**
* 两值之和
* @param nums 数组
* @param target 两值之和
* @return
*/
public int[] twoSum(int[] nums, int target) {
// 存入数据 key 为值 , value 为数组下标
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length ; i++){
int p = target - nums[i] ;
// 校验是否已存在和其相加之和为target 的数据在map 中
if (map.containsKey(p)) {
return new int[]{map.get(p),i};
}
map.put(nums[i],i);
}
return null;
}