-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTwoSum.java
More file actions
104 lines (96 loc) · 3.09 KB
/
Copy pathTwoSum.java
File metadata and controls
104 lines (96 loc) · 3.09 KB
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
101
102
103
/**
* <p>给定一个整数数组 <code>nums</code> 和一个整数目标值 <code>target</code>,请你在该数组中找出 <strong>和为目标值 </strong><em><code>target</code></em> 的那 <strong>两个</strong> 整数,并返回它们的数组下标。</p>
*
* <p>你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。</p>
*
* <p>你可以按任意顺序返回答案。</p>
*
* <p> </p>
*
* <p><strong>示例 1:</strong></p>
*
* <pre>
* <strong>输入:</strong>nums = [2,7,11,15], target = 9
* <strong>输出:</strong>[0,1]
* <strong>解释:</strong>因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
* </pre>
*
* <p><strong>示例 2:</strong></p>
*
* <pre>
* <strong>输入:</strong>nums = [3,2,4], target = 6
* <strong>输出:</strong>[1,2]
* </pre>
*
* <p><strong>示例 3:</strong></p>
*
* <pre>
* <strong>输入:</strong>nums = [3,3], target = 6
* <strong>输出:</strong>[0,1]
* </pre>
*
* <p> </p>
*
* <p><strong>提示:</strong></p>
*
* <ul>
* <li><code>2 <= nums.length <= 10<sup>4</sup></code></li>
* <li><code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code></li>
* <li><code>-10<sup>9</sup> <= target <= 10<sup>9</sup></code></li>
* <li><strong>只会存在一个有效答案</strong></li>
* </ul>
*
* <p><strong>进阶:</strong>你可以想出一个时间复杂度小于 <code>O(n<sup>2</sup>)</code> 的算法吗?</p>
* <div><div>Related Topics</div><div><li>数组</li><li>哈希表</li></div></div><br><div><li>👍 12518</li><li>👎 0</li></div>
*/
package leetcode1;
import java.util.HashMap;
import java.util.Map;
public class TwoSum {
public static void main(String[] args) {
Solution solution = new TwoSum().new Solution();
}
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{i, map.get(target - nums[i])};
}
map.put(nums[i], i);
}
return new int[0];
}
}
/**
* hash法
*/
class Solution2 {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
Integer j = map.get((target - nums[i]));
if (j == null) {
map.put(nums[i], i);
}
return new int[]{i, j};
}
return new int[0];
}
}
/**
* 两层循环,暴力遍历
*/
class Solution3 {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length - 1; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return new int[0];
}
}
}