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
22 changes: 22 additions & 0 deletions contains-duplicate/samcho0608.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import java.util.HashSet;

// link: https://leetcode.com/problems/contains-duplicate/description/
// difficulty: Easy
class Solution {
// Problem:
// * return: does any value appear more than once in the array
// Solution:
// * Time Complexity: O(N)
// * Space Complexity: O(N)
public boolean containsDuplicate(int[] nums) {
// Space Complexity: O(N)
HashSet<Integer> uniqNums = new HashSet<>();

// Time Complexity: O(N)
for(int num : nums) {
if(!uniqNums.add(num)) return true;
}
Comment on lines +16 to +18
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 내 값 체크 유무를 contains() 메소드를 주로 떠올리는데,
HashSet의 add() 메소드 리턴 값을 이용하신 부분에서 인상깊었습니다.


return false;
}
}
35 changes: 35 additions & 0 deletions house-robber/samcho0608.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// link: https://leetcode.com/problems/house-robber/description/
// difficulty: Medium
class Solution {
// Problem:
// * can't rob two adj houses in the same night
// * return: max amount of money robbale in one night
// Solution:
// * Time Complexity: O(N)
// * Space Complexity: O(N)
public int rob(int[] nums) {
if(nums.length == 1) return nums[0];
if(nums.length == 2) return Math.max(nums[0], nums[1]);

// maxSum[i] = max sum possible with nums[i]
int[] maxSum = new int[nums.length];
maxSum[0] = nums[0];
maxSum[1] = nums[1];

for(int i = 2; i < nums.length; i++) {
if(i == 2) {
maxSum[i] = nums[i] + maxSum[i-2];
continue;
}

// adj houses(i-1) can't be robbed
// choices are:
// 1. i-2 th house (choosing without skipping a house)
// 2. i-3 th house (choosing with skipping a house)
// * choosing < i-4 th houses wouldn't be optimal because it'll be missing either of 1. or 2.
maxSum[i] = nums[i] + Math.max(maxSum[i-2], maxSum[i-3]);
}

return Math.max(maxSum[nums.length-2], maxSum[nums.length-1]);
}
}
40 changes: 40 additions & 0 deletions longest-consecutive-sequence/samcho0608.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import java.util.HashSet;
import java.util.Set;

// link: https://leetcode.com/problems/longest-consecutive-sequence/
// difficulty: Medium
class Solution {
// Problem:
// * nums is unsorted
// * return: length of longest consecutive elements sequence
// * req: O(N) time
// Solution:
// * Time Complexity: O(N)
// * Space Complexity: O(N)
public int longestConsecutive(int[] nums) {
// Time Complexity: O(N)
// Space Complexity: O(N)
Set<Integer> uniq = new HashSet<>();
for(int num : nums) {
uniq.add(num);
}

// Time Complexity: O(N)
// * nested loop but is O(N) due to skipping non-root element
int maxLen = 0;
for(int num : uniq) {
// skip if num isn't the root(aka first number in the sequence)
if(uniq.contains(num - 1)) continue;

// count till end of consecutive sequence
int len = 1;
for(int i = 1; uniq.contains(num + i); i++) {
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.

해당 부분에서 i 값이 따로 쓰이지 않아서 while문으로 작성하는 것도 나쁘지 않을 것 같습니다.

while(uniq.contains(num + i)) {
    len++;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

조건문이 i를 포함하고 있어서 사용하긴 해야합니다!

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.

아 그렇네요! 주의깊게 살폈어야 했는데, 말씀 주신 부분을 미처 고려하지 못했네요. 앞으로는 더 꼼꼼히 확인하도록 하겠습니다.

len++;
}

maxLen = Math.max(maxLen, len);
}

return maxLen;
}
}
70 changes: 70 additions & 0 deletions top-k-frequent-elements/samcho0608.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import java.util.*;

// link: https://leetcode.com/problems/top-k-frequent-elements/description/
// difficulty: Medium

// Time complexity: O(Nlogk)
// Space complexity: O(N)
class Solution1 {
// return: top k most freq elements
public int[] topKFrequent(int[] nums, int k) {
HashMap<Integer, Integer> freq = new HashMap<>();
// O (N)
for(int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1); // O(1)
}

// O (N log k)
PriorityQueue<int[]> heap = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
for(int num : freq.keySet()) {
int f = freq.get(num); // O(1)
heap.add(new int[]{num, f}); // O(log k)

if(heap.size() > k) heap.poll(); // O(log k)
}
Comment on lines +18 to +24
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.

PriorityQueue 내 요소 개수를 k개로 유지해서, O(NlogN)이 아닌 O(Nlogk)로 하신 방법이 흥미롭네요.


// O (N log k)
int[] result = new int[k];
for(int i = 0; i < k; i++) {
result[i] = heap.poll()[0]; // O(log k)
}

return result;
}
}

// Time complexity: O(N)
// Space complexity: O(N)
class Solution2 {
public int[] topKFrequent(int[] nums, int k) {
// count frequencies
Map<Integer, Integer> freq = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}

// bucket: index = frequency, value = list of numbers
List<List<Integer>> buckets = new ArrayList<>(nums.length + 1);
for (int i = 0; i <= nums.length; i++) {
buckets.add(new ArrayList<>());
}

for (var entry : freq.entrySet()) {
int num = entry.getKey();
int count = entry.getValue();
buckets.get(count).add(num);
}

// gather top k frequent elements
int[] result = new int[k];
int idx = 0;
for (int i = nums.length; i >= 0 && idx < k; i--) {
for (int num : buckets.get(i)) {
result[idx++] = num;
if (idx == k) break;
}
}

return result;
}
}
35 changes: 35 additions & 0 deletions two-sum/samcho0608.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.HashMap;
import java.util.Map;

// link: https://leetcode.com/problems/two-sum/description/
// difficulty: Easy
class Solution {
// Problem
// * exactly one solution
// * must use index only once
// * return: indices of two numbers that add up to `target`
// Solution:
// * Time Complexity: O(N)
// * Space Complexity: O(N)
public int[] twoSum(int[] nums, int target) {
// Space Complexity: O(N)
Map<Integer, Integer> indexByNum = new HashMap<>();

// Time Complexity: O(N)
for(int i = 0; i < nums.length; i++) {
int numI = nums[i];
indexByNum.put(numI, i);
}

// Time Complexity: O(N)
for(int i = 0; i < nums.length; i++) {
int numI = nums[i];
Integer compl = indexByNum.getOrDefault(target-numI, null);

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

return null;
}
}