-
-
Notifications
You must be signed in to change notification settings - Fork 245
[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
Changes from 12 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
2261b21
contains duplicate solution
846f4ae
two sum solution
1fac60a
lint fix
90b51aa
lint fix
4f3d5a2
lint fix
d4ab0dd
top k frequent elements solution
d12f16a
fix javadoc format, lint
498eef8
fix lint
ed4e7c1
fix lint
eacf342
fix lint
50e1fb5
fix missing end line breaks
c7312a0
longest consecutive sequence solution
842cba9
house robber solution
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | ||
|
||
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; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]; | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
최소 힙으로 빈도수를 기준으로 정렬해서 top K만 유지하는 방식, 너무 인상 깊었어요!
저는 단순 정렬로 풀 생각만 했는데 힙을 활용하니까 더 효율적인 풀이가 가능하네요. 한 수 배워갑니다 😊
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
감사합니다. 처음에 k개를 항상 유지해야 하나? 생각이 들어서 없이도 시도해봤는데 요소가 증가할 수록 공간 복잡도도 증가하고 요소가 추가될 때마다 정렬하는 요소의 갯수도 증가하므로 성능을 위해서 k개를 유지해야 하는 것 같습니다.
또한 k개를 유지하고 나머지를 버리지 않으면 정답이 나오지 않더라고요:)