题目:给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。
方法一:遍历每个元素x,查找是否存在一个值与 target -x 相等。
public int[] twoSum(int[] nums, int target) {
if (nums.length <2 || target < 0) throw new IllegalArgumentException("参数不合法!");
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] == target - nums[i]){
return new int[]{i,j};
}
}
}
throw new IllegalArgumentException("未找到匹配的参数!");
}
时间复杂度:O(n^2),空间复杂度:O(1)
方法二:空间换时间。第一次遍历数组将数组的元素和下标放至HashMap中,第二次遍历数组判断HashMap中是否存在target-num[i]的key,且不能为同一元素。
注:此方法不允许数组中存在重复元素。
public int[] twoSum(int[] nums, int target) {
if (nums.length < 2 || target < 0) throw new IllegalArgumentException("参数不合法!");
Integer size = new Double(nums.length / 0.75 + 1).intValue();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(size);
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i]) && map.get(target - nums[i]) != i) {
return new int[]{i, map.get(target - nums[i])};
}
}
throw new IllegalArgumentException("未找到匹配的参数!");
}
时间复杂度:O(n),空间复杂度:O(n)
方法三:同方法二,但只进行一次遍历
public int[] twoSum(int[] nums, int target) {
if (nums.length < 2 || target < 0) throw new IllegalArgumentException("参数不合法!");
Integer size = new Double(nums.length / 0.75 + 1).intValue();
HashMap<Integer, Integer> map = new HashMap<>(size);
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("未找到匹配的参数!");
}
时间复杂度:O(n),空间复杂度:O(n)
测试用例:
public static void main(String[] args) {
Solution s = new Solution();
int[] result = s.twoSum(new int[]{1,3,6,8,4},5);
// int[] result = s.twoSum(new int[0],3);
// int[] result = s.twoSum(new int[]{1,3,6,8,4},-1);
// int[] result = s.twoSum(new int[]{1,3,6,8,4},100);
for (int i:result) System.out.print(i + " ");
}