forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTessa1217.java
More file actions
50 lines (35 loc) ยท 1.45 KB
/
Tessa1217.java
File metadata and controls
50 lines (35 loc) ยท 1.45 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
import java.util.Map;
import java.util.HashMap;
class Solution {
// ์ ์ ๋ฐฐ์ด nums์ ์ ์ target๊ฐ ์ฃผ์ด์ง ๋ ๋ ์ ์์ ํฉ์ด target์ด ๋๋ ๋ฐฐ์ด ์์์ ์ธ๋ฑ์ค๋ฅผ ๋ฐํ
// ์
๋ ฅ๋ฐ์ ๋ฐฐ์ด์๋ ํ๋์ ํด๋ต๋ง ์กด์ฌํ๋ค๊ณ ๊ฐ์ ํ ์ ์์ผ๋ฉฐ ๊ฐ์ ์์๋ฅผ ํ ๋ฒ ์ด์ ์ฌ์ฉํ ์๋ ์๋ค.
// ๋ฐํํ๋ ์ธ๋ฑ์ค์ ์ ๋ ฌ์ ์ ๊ฒฝ์ฐ์ง ์์๋ ๋๋ค.
public int[] twoSum(int[] nums, int target) {
// ํํธ๋ฅผ ์ฐธ๊ณ ํ์ฌ ์๊ฐ ๋ณต์ก๋ O(n^2) ์ดํ๋ก ์ค์ด๊ธฐ
// ํํธ: Like maybe a hash map to speed up the search?
int[] answer = new int[2];
Map<Integer, Integer> numMap = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (numMap.containsKey(target - nums[i])) {
answer[0] = numMap.get(target - nums[i]);
answer[1] = i;
break;
}
numMap.put(nums[i], i);
}
return answer;
}
// public int[] twoSum(int[] nums, int target) {
// // ์ ์ฒด ํ์ ์งํ
// int[] answer = new int[2];
// for (int i = 0; i < nums.length - 1; i++) {
// for (int j = i + 1; j < nums.length; j++) {
// if (nums[i] + nums[j] == target) {
// answer[0] = i;
// answer[1] = j;
// }
// }
// }
// return answer;
// }
}