Skip to content
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
18 changes: 18 additions & 0 deletions contains-duplicate/heesun-task.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution {
public boolean containsDuplicate(int[] nums) {
// Create a set to track seen numbers
Set<Integer> seen = new HashSet<>();

// Loop through the array and return true if a duplicate is found
for (int num : nums) {
if (!seen.add(num)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Set의 add 함수가 boolean 값을 반환한다는 점을 이용하여 푼 점이 인상 깊었습니다.

return true;
}
}

return false;
}
}

// Time Complexity: O(n) on average
// Space Complexity: O(n)
40 changes: 40 additions & 0 deletions top-k-frequent-elements/heesun-task.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

class Solution {
public int[] topKFrequent(int[] nums, int k) {
// Count each number's frequency using a hash map.
Map<Integer, Integer> freq = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}

// Keep the top k numbers in a min-heap ordered by frequency.
PriorityQueue<Integer> heap = new PriorityQueue<>(
(a, b) -> Integer.compare(freq.get(a), freq.get(b))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

freq.get(a) - freq.get(b) 대신 compare 함수를 사용하여 overflow를 방지한 점이 좋습니다.

);

for (int num : freq.keySet()) {
if (heap.size() < k) {
heap.offer(num);
} else if (freq.get(num) > freq.get(heap.peek())) {
// Replace the least frequent number.
heap.poll();
heap.offer(num);
}
}

// Return the numbers in the heap.
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = heap.poll();
}

return result;
}
}

// Time Complexity: O(n + u log k)
// Space Complexity: O(u + k)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

k값은 u보다 클 수 없기 때문에 O(u) 로 표기해도 될 것 같습니다.

// n = nums.length, u = number of unique numbers
Loading