package practice;
import java.util.HashMap;
import java.util.Map;
public class Ecercise1两数之和 {
public static void main(String[] args) {
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
// 暴力求解①时间和内存占用过高
int[] temp = new int[2];// 用来存储那两个整数的下标
int[] num = new int[nums.length];// 复制数组
boolean is = false;
System.arraycopy(nums, 0, num, 0, nums.length);
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < num.length; j++) {
if (nums[i] + nums[j] == target && i != j) {
temp[0] = i;
temp[1] = j;
is = true;// 用来跳出外层循环
break;
}
}
if (is) {
break;
}
}
return temp;
}
// 暴力求解②时间和内存占用比①要少
public int[] twoSum2(int[] nums, int target) {
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 };
}
}
}
// 抛出的异常表明向方法传递了一个不合法或不正确的参数。
// 和try{}catch{}一样,也是java的一种异常捕获机制
throw new IllegalArgumentException("No two sum solution");
}
// 两遍遍历哈希表③比暴力求解②时间和内存占用更少
public int[] twoSum3(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
// 一遍遍历哈希表④和暴力求解②差不多
public int[] twoSum4(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
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("No two sum solution");
}
}
两数之和的一题多解
最新推荐文章于 2021-06-09 11:15:39 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)