首先两层for循环的是时间复杂度是 On^2, 在此就不说了.
所以我们这边要优化时间复杂度. 此时间复杂度为 n.
/**
* 两值之和
* @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;
}
来源:https://blog.csdn.net/bfy0914/article/details/100544207