1. 题目
给定一个整数数组nums和一个目标值target, 请你在该数组中找出和为目标值的那两个整数, 并返回他们的数组下标.
2. 备注
原题目中假设每种输入只会对应一个答案, 现在我们不要这种假设尝试下能不能解题…
3. 答案
3.1 暴力破解法
public class Solution1 {
public static void twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
if (nums[i] + nums[j] == target) {
System.out.println(i + ">>>" + j);
}
}
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 2, 2, 4};
int target = 4;
twoSum(nums, target);
}
}
答案如下:
1>>>2
1>>>3
2>>>3
3.2 两遍哈希表
import java.util.HashMap;
/**
* @author v_younli
* 因为数组中的元素是存在重复数据的, 所以映射到哈希表之后老的K会被覆盖
* [(1,0),(2,3),(4,4)]
* 所以结果会少一种情况
*/
public class Solution2 {
public static void twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int other;
// 第一遍将数据放入哈希表
for (int i = 0; i < nums.length - 1; i++) {
map.put(nums[i], i);
}
// 第二遍先计算差值, 然后去哈希表中找有没有
for (int i = 0; i < nums.length; i++) {
other = target = nums[i];
if (map.containsKey(other) && map.get(other) != i) {
System.out.println(i + ">>>" + map.get(other));
}
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 2, 2, 4};
int target = 4;
twoSum(nums, target);
}
}
答案如下:
1>>>3
2>>>3
哎? 这里怎么少了一种情况啊? 代码的注释上已经解释了
3.3 一遍哈希表
import java.util.HashMap;
/**
* i=0 other=3 map是空
* i=1 other=2 map是[(1,0)]
* i=2 other=2 map是[(1,0), (2,1)] 这里会输出 2>>>1
* i=3 other=2 map是[(1,0), (2,2)] 这里会输出 3>>>2
* i=4 other=0 map是[(1,0), (2,3)]
*/
public class Solution3 {
public static void twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int other;
// 第一遍先计算差值检查数据存在否, 然后将数据放入哈希表
for (int i = 0; i < nums.length - 1; i++) {
other = target - nums[i];
if (map.containsKey(other) && map.get(other) != i) {
System.out.println(i + ">>>" + map.get(other));
}
map.put(nums[i], i);
}
}
public static void main(String[] args) {
int[] nums = {1, 2, 2, 2, 4};
int target = 4;
twoSum(nums, target);
}
}
答案如下:
2>>>1
3>>>2
3.4 双指针
import java.util.Arrays;
public class Solution {
public static int[] twoSum(int[] nums, int target) {
int m = 0, n = 0, k = 0;
int[] res = new int[2];
int[] tmp1 = new int[nums.length];
// 将数组备份出来一份
System.arraycopy(nums, 0, tmp1, 0, nums.length);
// 排序
Arrays.sort(nums);
for (int i = 0, j = nums.length - 1; i < j; ) {
if (nums[i] + nums[j] < target)
i++;
else if (nums[i] + nums[j] > target)
j--;
else if (nums[i] + nums[j] == target) {
m = i;
n = j;
break;
}
}
// 取下标
for (k = 0; k < nums.length; k++) {
if (tmp1[k] == nums[m]) {
res[0] = k;
break;
}
}
for (int i = 0; i < nums.length; i++) {
if (tmp1[i] == nums[n] && i != k)
res[1] = i;
}
return res;
}
public static void main(String[] args) {
int[] nums = {1, 2, 2 ,2, 4};
int target = 4;
int[] ints = twoSum(nums, target);
System.out.println(ints[0] + ">>>" + nums[1]);
}
}
答案如下:
1>>>2
4. 总结
按照原题目的话四种方式都是可以的
如果不限定只有一个答案的话就只有暴力破解是符合条件的~