Skip to content

Commit 651d248

Browse files
authored
Merge pull request DaleStudy#1155 from Yn3-3xh/main
[Yn3-3xh] WEEK 01 solutions
2 parents 9987cd5 + d87b7ed commit 651d248

File tree

5 files changed

+222
-0
lines changed

5 files changed

+222
-0
lines changed

contains-duplicate/Yn3-3xh.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/*
2+
[문제풀이]
3+
time: O(N), space: O(N)
4+
- 같은 수가 하나라도 있으면 true
5+
- 모든 수가 다르면 false
6+
7+
[회고]
8+
ArrayList vs Set
9+
ArrayList: O(N^2), 매번 리스트를 처음부터 검색해야 하며, n번 반복
10+
Set : O(N) , 내부적으로 해시 테이블을 사용하여 중복 확인을 O(1)에 수행
11+
따라서 중복 검사에서 Set 더 효율적
12+
13+
set.add()의 return 자료형은 boolean 이다.
14+
이후에는 if(!set.add()) 처럼 사용해도 좋을 듯.
15+
*/
16+
class Solution {
17+
public boolean containsDuplicate(int[] nums) {
18+
Set<Integer> set = new HashSet<>();
19+
for (int num : nums) {
20+
if (set.contains(num)) {
21+
return true;
22+
}
23+
set.add(num);
24+
}
25+
return false;
26+
}
27+
}

house-robber/Yn3-3xh.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*
2+
[문제풀이]
3+
(X) 주어진 nums 배열에서 index 홀수의 합과 짝수의 합을 비교해보자.
4+
class Solution {
5+
public int rob(int[] nums) {
6+
if (nums.length == 1) {
7+
return nums[0];
8+
}
9+
10+
for (int i = 1; i <= nums.length; i++) {
11+
int beforeStepIndex = i - 2;
12+
if (beforeStepIndex >= 1) {
13+
nums[i - 1] += nums[beforeStepIndex - 1];
14+
}
15+
}
16+
return Math.max(nums[nums.length - 1], nums[nums.length - 2]);
17+
}
18+
}
19+
>> 바로 옆이 아니어도 된다.
20+
21+
(O) 현재 num과 이전 num을 비교하여, 큰 값을 기준으로 더한다.
22+
time: O(N), space: O(1)
23+
class Solution {
24+
public int rob(int[] nums) {
25+
int prevNum = 0;
26+
int sum = 0;
27+
for (int num : nums) {
28+
int temp = Math.max(sum, prevNum + num);
29+
prevNum = sum;
30+
sum = temp;
31+
}
32+
return sum;
33+
}
34+
}
35+
>> 공간복잡도 최적화 솔루션으로, dp 보다 직관적이지 않아, 메모리 사용이 제한되거나 입력 크기가 매우 클 때 사용하는 것이 좋을 듯
36+
37+
time: O(N), space: O(N)
38+
class Solution {
39+
public int rob(int[] nums) {
40+
if (nums.length == 1) {
41+
return nums[0];
42+
}
43+
44+
int[] dp = new int[nums.length];
45+
dp[0] = nums[0];
46+
dp[1] = Math.max(nums[0], nums[1]);
47+
48+
for (int i = 2; i < nums.length; i++) {
49+
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
50+
}
51+
return dp[nums.length - 1];
52+
}
53+
}
54+
>> 공간복잡도는 좀 더 높지만, 직관적이다.
55+
[회고]
56+
개발은 혼자하는 것이 아니기도 하고, 디버깅하기 쉽게 직관적인 DP로 푸는게 좋지 않을까?..?
57+
*/
58+
class Solution {
59+
public int rob(int[] nums) {
60+
if (nums.length == 1) {
61+
return nums[0];
62+
}
63+
64+
int[] dp = new int[nums.length];
65+
dp[0] = nums[0];
66+
dp[1] = Math.max(nums[0], nums[1]);
67+
68+
for (int i = 2; i < nums.length; i++) {
69+
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
70+
}
71+
return dp[nums.length - 1];
72+
}
73+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
[문제풀이]
3+
time: O(N), space: O(N)
4+
- 중복 제거
5+
- 연속된 횟수 max 구하기
6+
-- 연속된 숫자 그룹 중 첫번째부터 시작되도록
7+
8+
[회고]
9+
연속된 숫자 그룹 중 첫번째부터 시작되도록 하는 부분에서 막혔다..
10+
차분히 생각해보면 무리없이 풀 수 있지 않았을까..
11+
*/
12+
class Solution {
13+
public int longestConsecutive(int[] nums) {
14+
if (nums.length == 0) {
15+
return 0;
16+
}
17+
18+
Set<Integer> numsSet = new HashSet<>();
19+
for (int num : nums) {
20+
numsSet.add(num);
21+
}
22+
23+
int maxCount = 1;
24+
for (int num : numsSet) {
25+
if (!numsSet.contains(num - 1)) {
26+
int count = 1;
27+
int currentNum = num;
28+
while (numsSet.contains(currentNum + 1)) {
29+
count++;
30+
currentNum++;
31+
}
32+
maxCount = Math.max(maxCount, count);
33+
}
34+
}
35+
return maxCount;
36+
}
37+
}

top-k-frequent-elements/Yn3-3xh.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
[문제풀이]
3+
time: O(N log N), space: O(N + k)
4+
- 주어진 Nums의 중복된 수의 갯수를 Map에 담고,
5+
- 역정렬하면,
6+
- k만큼 뽑기
7+
class Solution1 {
8+
public int[] topKFrequent(int[] nums, int k) {
9+
Map<Integer, Integer> counting = new HashMap<>();
10+
for (int num: nums) {
11+
int numCount = counting.getOrDefault(num, 0) + 1;
12+
counting.put(num, numCount);
13+
}
14+
15+
List<Map.Entry<Integer, Integer>> sortedCounting = new ArrayList<>(counting.entrySet());
16+
sortedCounting.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
17+
18+
int[] result = new int[k];
19+
for (int i = 0; i < k; i++) {
20+
result[i] = sortedCounting.get(i).getKey();
21+
}
22+
23+
return result;
24+
}
25+
}
26+
27+
time: O(N log k), space: O(N + k)
28+
- PriorityQueue 사용
29+
- value로 역정렬 설정
30+
- key로 queue에 add
31+
32+
[회고]
33+
첫번째 풀이는 역정렬 하는 부분이 미숙했고,
34+
두번째 풀이는 PriorityQueue를 사용하는데 처음 써본다.. (익히자!)
35+
*/
36+
class Solution {
37+
public int[] topKFrequent(int[] nums, int k) {
38+
Map<Integer, Integer> counting = new HashMap<>();
39+
for (int num: nums) {
40+
int numCount = counting.getOrDefault(num, 0) + 1;
41+
counting.put(num, numCount);
42+
}
43+
44+
Queue<Integer> queue = new PriorityQueue<>((count1, count2) ->
45+
counting.get(count2) - counting.get(count1));
46+
queue.addAll(counting.keySet());
47+
48+
int[] result = new int[k];
49+
for (int i = 0; i < k; i++) {
50+
result[i] = queue.poll();
51+
}
52+
return result;
53+
}
54+
}

two-sum/Yn3-3xh.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
[문제풀이]
3+
time: O(N), space: O(N)
4+
- nums 배열에 있는 두 수를 더한 값 = target
5+
- 더할 때 한 번씩만 사용
6+
7+
[회고]
8+
O(N^2) 보다 줄일 수 있을까?
9+
결국 힌트3 까지 봐버렸다..
10+
11+
nums 배열을 돌며 target-nums[i] 값을 key로, i를 value로, HashMap에 저장하면,
12+
배열을 돌다 해당 index의 값 nums[i]가 HashMap의 key와 일치하면,
13+
그 key의 value인 index를 뽑으면 된다.
14+
(Hash Table을 사용하면 키를 해싱하여 접근하기 때문에 조회가 빠르다!)
15+
16+
유사한 문제가 나올 때 2중 for문이 이런 접근 방식이 먼저 떠올랐으면 좋겠다.
17+
*/
18+
19+
class Solution {
20+
public int[] twoSum(int[] nums, int target) {
21+
Map<Integer, Integer> seen = new HashMap<>();
22+
for (int i = 0; i < nums.length; i++) {
23+
int diff = target - nums[i];
24+
if (seen.containsKey(diff)) {
25+
return new int[]{seen.get(diff), i};
26+
}
27+
seen.put(nums[i], i);
28+
}
29+
return null;
30+
}
31+
}

0 commit comments

Comments
 (0)