题目地址: https://leetcode-cn.com/problems/two-sum/
题目说明:
给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标.
你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使用两遍.
题目事例:
给定nums = [2, 7, 11, 15], target = 9
因为nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
题目分析:
你可以假设每种输入只会对应一个答案.但是,数组中同一个元素不能使用两遍
这两个说明其实是核心所在.
方法一:两遍hash方法,使用hash将时间复杂度降低为O(n)
public int[] twoSum(int[] nums, int target) {
// 1.校验参数的有效性
if (nums == null || nums.length == 0) { return new int[0]; }
// 2.将数据保存保存到hash表中
Map<Integer, Integer> hash = new HashMap<>();
for (int i=0; i<nums.length; i++) {
hash.put(nums[i], i);
}
// 3.遍历数据进行查询
for (int i=0; i<nums.length; i++) {
int val = target - nums[i];
if (hash.containsKey(val) && hash.get(val) != i) {
return new int[]{i, hash.get(val)};
}
}
return new int[0];
}
方法二:一遍hash方法,使用hash将时间复杂度降低为O(n)
// 1.采用1遍hash方式处理
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> valAndIdex = new HashMap<>();
// 2.遍历当前数据获取目标数据
for (int index = 0; index < nums.length; index++) {
int temp = target - nums[index];
Integer valIndex = valAndIdex.get(temp);
if (valIndex != null && valIndex != index) {
return new int[]{valIndex, index};
}
valAndIdex.put(nums[index], index);
}
throw new IllegalArgumentException("No two sum solution");
}