-
Notifications
You must be signed in to change notification settings - Fork 0
/
TwoNumSum.java
100 lines (82 loc) · 2.53 KB
/
TwoNumSum.java
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package com.bcxiaobao.leetcode.algorithm;
import java.util.Arrays;
import java.util.HashMap;
/**
* Created by IntelliJ IDEA.
* User: lianxiaobao
* Date: 2019-12-02
* Time: 22:16
*
*
*
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
*
* 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
*
* 示例:
*
* 给定 nums = [2, 7, 11, 15], target = 9
*
* 因为 nums[0] + nums[1] = 2 + 7 = 9
* 所以返回 [0, 1]
*/
public class TwoNumSum {
public static void main(String[] args) {
int[] nums = new int[]{3, 2, 4, 15};
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(twoSumOrdinary(nums, 6)));
System.out.println(Arrays.toString(twoSumByMap(nums, 6)));
System.out.println(Arrays.toString(twoSumOrd(nums, 6)));
}
public static int[] twoSumOrdinary(int[] nums, int target) {
int[] num = new int[2];
for (int i = 0; i <nums.length ; i++) {
for (int j = nums.length-1; j >i ; j--) {
if((nums[i]+ nums[j]) == target){
num[0] = i;
num[1] = j;
return num;
}
}
}
return num;
}
public static int[] twoSumOrd(int[] nums, int target){
int[] num = new int[2];
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target){
num[0] = i;
num[1] = j;
return num;
}
}
}
return num;
}
/**
* leetcode 测试性能提高十倍
* @param nums
* @param target
* @return
*/
public static int[] twoSumByMap(int[] nums,int target){
int[] num = new int[2];
// 建立k-v ,一一对应的哈希表
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
num[0] = i;
num[1] = map.get(nums[i]);
return num;
}
// 将数据存入 key为补数 ,value为下标
map.put(target-nums[i], i);
}
return num;
}
public static Long now(){
long l = System.currentTimeMillis();
return l;
}
}