forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGotprgmer.java
More file actions
37 lines (34 loc) ยท 1.42 KB
/
Gotprgmer.java
File metadata and controls
37 lines (34 loc) ยท 1.42 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
// ์ด์ ์ ํฌํฌ์ธํฐ๋ฅผ ํ์ฉํ์ฌ ์๋ํ์ง๋ง ์ค๋ณต๋ ๊ฐ๋ค์ ์ฒ๋ฆฌํ๋๋ฐ ์ด๋ ค์์ด ์์์ต๋๋ค.
// ๊ทธ๋์ ํด๋ต์ ๋ณด์๊ณ ์๋ก์ด ๋ฐฉ๋ฒ์ผ๋ก ํ์ด๋ณด์์ต๋๋ค.
// ์๋ก ๋ค๋ฅธ i์ j ์ธ๋ฑ์ค๋ฅผ 2์ค for๋ฌธ์ผ๋ก ์งํํ๋ฉด์
// i์ j์ฌ์ด ์๋ค์ set์ผ๋ก ๊ด๋ฆฌํฉ๋๋ค.
// set์ -nums[i]-nums[j]๊ฐ ์กด์ฌํ๋ฉด ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์ถ๊ฐํฉ๋๋ค.
// ์๊ฐ๋ณต์ก๋ : O(N^2)
// ๊ณต๊ฐ๋ณต์ก๋ : O(N)
class SolutionGotprgmer {
public List<List<Integer>> threeSum(int[] nums) {
// ๊ฒฐ๊ณผ๋ฅผ ์ ์ฅํ ๋ฆฌ์คํธ
List<List<Integer>> result = new ArrayList<>();
Set<Integer> set;
Set<List<Integer>> resultSet = new HashSet<>();
List<Integer> numList;
// ๋ฆฌ์คํธ ์ ๋ ฌ
Arrays.sort(nums);
for(int i=0;i<nums.length-2;i++){
if (i > 0 && nums[i - 1] == nums[i]) continue;
set = new HashSet<>();
for(int j=i+1;j<nums.length;j++){
int checkNum = nums[i]+nums[j];
if(set.contains(-checkNum)){
numList = new ArrayList<>(Arrays.asList(nums[i], -checkNum, nums[j]));
if(!resultSet.contains(numList)){
result.add(numList);
resultSet.add(numList);
}
}
set.add(nums[j]);
}
}
return result;
}
}