题目:两数之和
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6 输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6 输出:[0,1]
题目链接如下:
答案:
方法一:暴力法
package com.atguigu.algorithm.arrays;
public class TwoSum {
//方法一:暴力法,穷举所有两数组合
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
//双重for循环
for (int i = 0; i < n - 1; i++) {
for (int j = i+1; j < n; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
//如果找不到,抛出异常
throw new IllegalArgumentException("no solution");
}
public static void main(String[] args) {
int[] input = {2, 7, 11, 15};
int target = 9;
TwoSum ts = new TwoSum();
int[] output = ts.twoSum(input, target);
for (int index : output) {
System.out.print(index + "\t");
}
}
}
时间复杂度:O(n^2)
空间复杂度:O(1)
方法二:两遍哈希表
public class TwoSum {
// 第二种解法:用哈希表计算,也需要循环两次
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < n; i++) {
int thatNum = target - nums[i];
if (map.containsKey(thatNum) && map.get(thatNum) != i) {
return new int[]{i, map.get(thatNum)};
}
}
throw new IllegalArgumentException("no solution");
}
public static void main(String[] args) {
int[] input = {2, 7, 11, 13};
int target = 9;
TwoSum ts = new TwoSum();
int[] output = ts.twoSum(input, target);
for (int index : output) {
System.out.println(index);
}
}
}
时间复杂度:O(n)
空间复杂度:O(n)
方法三:一遍哈希表
public class TwoSum {
//第三种方法:哈希表,只用一次
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
int thatNum = target - nums[i];
if (map.containsKey(thatNum) && map.get(thatNum) != i) {
// return new int[]{i, map.get(thatNum)};结果是[1,0]
return new int[]{map.get(thatNum), i}; //结果是[0,1]
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("no solution");
}
public static void main(String[] args) {
int[] input = {2, 7, 11, 13};
int target = 9;
TwoSum ts = new TwoSum();
int[] output = ts.twoSum(input, target);
for (int index : output) {
System.out.println(index);
}
}
}
时间复杂度:O(n)
空间复杂度:O(n)
但少一次循环,更简洁
说明:
用平台做记录,不喜勿喷,谢谢