-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
48 lines (45 loc) · 1.36 KB
/
TwoSum.java
File metadata and controls
48 lines (45 loc) · 1.36 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
package com.cier.solution.array;
import java.util.HashMap;
/**
* 两数之和
* https://leetcode-cn.com/problems/two-sum/description/
*/
public class TwoSum {
/**
* 时间复杂度O(n^2)
* Runtime: 19 ms, faster than 36.03% of Java online submissions for Two Sum.
* Memory Usage: 37.5 MB, less than 98.44% of Java online submissions for Two Sum.
* @param nums
* @param target
* @return
*/
public int[] twoSum1(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i, j};
}
}
}
return null;
}
/**
* 时间复杂度O(n)
*Runtime: 2 ms, faster than 99.39% of Java online submissions for Two Sum.
* Memory Usage: 37.3 MB, less than 98.47% of Java online submissions for Two Sum.
* @param nums
* @param target
* @return
*/
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int num = target - nums[i];
if (map.containsKey(num)) {
return new int[]{map.get(num), i};
}
map.put(nums[i], i);
}
return null;
}
}