Skip to content

[jinvicky] WEEK 01 solutions #1681

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jul 27, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions contains-duplicate/jinvicky.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import java.util.*;

class Solution {
public boolean containsDuplicate(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) return true;
}
return false;
}
}
19 changes: 19 additions & 0 deletions house-robber/jinvicky.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//dp[0] -> 1번째 집 털이 수완으로 초기화
//dp[1] -> -2집 털이+지금집 털이가 -1집 털이보다 수완이 좋다. = -2집 털이(0)+지금집 털이 = 7
//dp[2] -> -2집 털이+지금집 털이가 -1집 털이보다 수완이 좋다. = -2집 털이+지금집 털이 = 11
//dp[3] -> -2집 털이+지금집 털이가 -1집 털이보다 수완이 좋다. = -2집 털이+지금집 털이 = 11 (>10)
//dp[4] -> -2집 털이+지금집 털이가 -1집 털이보다 수완이 좋다. = -2집 털이+지금집 털이 = 12 (>10)
class Solution {
public int rob(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];

for (int i = 1; i < nums.length; i++) {
int prev2AndNowRob = (i - 2 < 0 ? 0 : dp[i - 2]) + nums[i];
int prev1Rob = dp[i - 1];

dp[i] = Math.max(prev2AndNowRob, prev1Rob);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

변수 네이밍이 직관적이어서 로직을 이해하기 정말 쉬웠습니다! 그리고 i == 1 일 때의 예외처리도 꼼꼼하게 해주신 것 같아요 🤩

추가로 풀이의 DP 점화식이 dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])인 것으로 보이는데요, 이때 dp[i - 2]dp[i - 1] 값만 필요하기 때문에 O(n) space의 dp list가 아닌 O(1) space의 변수 두 개로 공간 복잡도 최적화를 더 해볼 수 있을 것 같습니다!

첫 주 고생 많으셨습니다~! 🚀

Copy link
Contributor Author

@jinvicky jinvicky Jul 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아... 항상 dp 문제가 나오면 무의식적으로 입력값의 길이로 dp 배열을 만드는 습관이 있는데 다시 짚어주셔서 감사합니다.
다음 dp 풀이 때는 공간 복잡도 최적화를 한번 더 생각해보겠습니다. 정말 감사합니다!

}
return dp[nums.length - 1];
}
}
32 changes: 32 additions & 0 deletions longest-consecutive-sequence/jinvicky.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import java.util.HashSet;
import java.util.Set;

// 연속적인 숫자의 길이를 구하는 것이기 때문에 이전, 다음 수가 집합의 일부인지를 파악해야 한다.
// map, set 자료구조를 사용하면 조회 성능을 O(1)로 높일 수 있다.
// 어려웠던 점은 연속적인 숫자의 start가 되냐 여부 조건을 떠올리는 것이었다. while문이 약해서 length++하는 로직이 힘들었다.
// 문제의 조건은 배열 내에서의 연속적인 숫자의 길이이기 때문에 while을 사용해도 성능 이슈 걱정할 필요가 없었다.
class Solution {
public int longestConsecutive(int[] nums) {
Set<Integer> set = new HashSet<>();

for (int n : nums) {
set.add(n);
}

int maxLength = 0;

for (int n : nums) {
if (!set.contains(n - 1)) { // 내 이전 숫자가 집합에 없다 == 내가 최소 숫자다.
int length = 1;

while (set.contains(n + length)) {
length++;
}

maxLength = Math.max(length, maxLength);
}
}

return maxLength;
}
}
42 changes: 42 additions & 0 deletions top-k-frequent-elements/jinvicky.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

class Solution {
public int[] topKFrequent(int[] nums, int k) {
// [풀이]
// 1. <숫자: 빈도수>를 저장하는 HashMap과 [빈도수, 숫자]를 저장하는 PriorityQueue를 선언한다.
// 2. HashMap에 숫자별로 빈도수를 함께 저장해서 해시테이블을 만든다.
// [우선순위 큐에 사용된 자료구조]
// 1. 별도 클래스를 선언
// 2. 요구사항 자료형 배열을 선언한다.
// 처음에는 별도 클래스를 선언했다가 값이 2개이며 알고리즘 로직 자체가 어려워서 int[] 구조로 풀이했다.
// (주로 알고리즘이 어려우면 가독성이 나쁘더라도 자료구조를 단순화하는 습관이 있다)
// [어려웠던 점]
// 1. 우선순위 큐는 매번 요소가 추가될 때마다 내부 정렬을 수행하기 때문에 연산을 수행하면서 k개를 유지해야 한다.
// 또한 기존 [빈도수, 숫자]를 버려야만 올바른 답을 도출할 수 있었다.
// 2. [숫자, 빈도수]로 저장하는 것만 생각했더니 내부 정렬을 어떻게 하지 못해서 굉장히 고민했다. 정답은 반대였다.

int[] answer = new int[k];

Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) {
map.put(n, map.getOrDefault(n, 0) + 1);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

최소 힙으로 빈도수를 기준으로 정렬해서 top K만 유지하는 방식, 너무 인상 깊었어요!
저는 단순 정렬로 풀 생각만 했는데 힙을 활용하니까 더 효율적인 풀이가 가능하네요. 한 수 배워갑니다 😊

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

감사합니다. 처음에 k개를 항상 유지해야 하나? 생각이 들어서 없이도 시도해봤는데 요소가 증가할 수록 공간 복잡도도 증가하고 요소가 추가될 때마다 정렬하는 요소의 갯수도 증가하므로 성능을 위해서 k개를 유지해야 하는 것 같습니다.
또한 k개를 유지하고 나머지를 버리지 않으면 정답이 나오지 않더라고요:)


for (int key : map.keySet()) {
pq.add(new int[]{map.get(key), key});
if (pq.size() > k) {
pq.poll();
}
}

for (int i = 0; i < k; i++) {
if (!pq.isEmpty()) {
answer[i] = pq.poll()[1];
}
}
return answer;
}
}
36 changes: 36 additions & 0 deletions two-sum/jinvicky.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import java.util.HashMap;
import java.util.Map;

/**
* 본래 brute force로 이중 for문으로 풀었다가 map으로 최적화.
*/
class Solution {

public int[] twoSumByBruteForce(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 new int[2];
}

public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> numberMap = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
int required = target - nums[i];
Integer index = numberMap.get(required);

if (index != null) {
return new int[]{index, i};
}

numberMap.put(nums[i], i);
}

return new int[2];
}
}