Nameless Site

But one day, you will stand before its decrepit gate,without really knowing why.

0%

两数之和

来源Leetcode第一题两数之和

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]


暴力

暴力解法来自于2个半月之前,两轮循环遍历数组,找到目标元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int* res = (int *)malloc(sizeof(int) * 2);
for(int i = 0; i < numsSize-1; i++) {
for(int j = i + 1; j < numsSize; j++) {
if(nums[i] + nums [j] == target) {
res[0] = i;
res[1] = j;
*returnSize = 2;
return res;
}
}
}
return res;
}

哈希表

来自于题解

建立哈希表存放元素值以及位置值,每次查找target - nums[i]

1
2
3
4
5
6
7
8
9
10
public int[] twoSum(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);
}
return new int[];
}

POJ上的两数之和

来自POJ2366题,提交WA,问题未知。

问题代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = false;
int len1 = in.nextInt();
int [] A = new int[len1];
for(int i = 0; i < len1; i++)
A[i] = in.nextInt(); //数组A升序
int len2 = in.nextInt();
int [] B = new int[len2];
for(int i = 0 ; i < len2;i++)
B[i] = in.nextInt(); //数组B降序
int temp;
Map<Integer,Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < len1 + len2 ; i++){
int complement;
if(i >= len1){
temp = B[i - len1];
complement = 10000 - temp;
}else{
temp = A[i];
complement = 10000 - A[i];
}
if(map.containsKey(complement)){
flag = true;
break;
}
map.put(temp,i);
}
if(flag)
System.out.println("YES");
else
System.out.println("NO");
}
}