Skip to content

[권동현] Week 1 #629

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 6 commits into from
Dec 14, 2024
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
35 changes: 35 additions & 0 deletions contains-duplicate/kdh-92.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution {
public boolean containsDuplicate(int[] nums) {
/**
* Constraints
* - 1 <= nums[] <= 10^5
* - -10^9 <= nums[i] <= 10^9
*
* Output
* - true : 중복 값 존재
* - false : 모든 값이 유일
*/

// 해결법 1 (HashMap 방식 - HashSet 유사)
// 시간복잡도: O(N), 공간 복잡도 : O(N)
Map<Integer, Integer> countMap = new HashMap<>();

for (int num: nums) {
int count = countMap.getOrDefault(num, 0) + 1;
if (count > 1) return true;
Copy link
Member

Choose a reason for hiding this comment

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

자바 Map에는 getOrDefault이라는 메소드가 있군요!

질문이 있는데 혹시 HashSet add 메소드의 반환값 boolean을 사용하는 게 아니라 HashMap을 사용하신 이유가 있나요?

Copy link
Contributor Author

@kdh-92 kdh-92 Dec 5, 2024

Choose a reason for hiding this comment

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

위 문제 관련해서는 HashSet과 HashMap 사용했을 때 성능이 크게 다르지 않은 것 같다고 판단했습니다!

Leetcode Runtime & Memory 성능

  • HashSet - 8ms / Beats 92.15% & 61.50 MB / Beats 5.63%
  • HashMap - 14ms / Beats 41.10% & 57.94 MB / Beats 52.22%
    (생각보다는 차이가 있네요!?)

추가로 코테를 풀면서 getOrDefault를 사용하게 되는 경우가 많더라구요!
이전에 문제 푸는 과정에서 해당 메서드 이름이 생각이 안 나서 고생했던 적이 있어 익숙해지고 싶어 HashMap을 사용해봤습니다!

countMap.put(num, count);
}

return false;

// 해결법 2 (정렬)
// 시간 복잡도 : O(N log N), 공간 복잡도 : O(1)
Arrays.sort(nums);

for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1]) return true;
}

return false;
}
}
29 changes: 29 additions & 0 deletions house-robber/kdh-92.java
Copy link
Member

@dusunax dusunax Dec 10, 2024

Choose a reason for hiding this comment

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

LGTM👍
저는 dp로만 풀이했는데 두 번째 방식도 배워갑니다

Copy link
Contributor

Choose a reason for hiding this comment

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

@dusunax 보시기에 approve해도 괜찮겠다 싶으시면 approve까지 직접 눌러주세요~

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
class Solution {
public int rob(int[] nums) {
// (1) dp
// int n = nums.length;

// if (n == 1) return nums[0];

// int[] dp = new int[n];

// dp[0] = nums[0];
// dp[1] = Math.max(nums[0], nums[1]);

// for (int i = 2; i < n; i++) {
// dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]);
// }

// return dp[n - 1];

// (2) 인접 값 비교
int prev = 0, curr = 0;
for (int num : nums) {
int temp = curr;
curr = Math.max(num + prev, curr);
prev = temp;
}

return curr;
}
}
61 changes: 61 additions & 0 deletions longest-consecutive-sequence/kdh-92.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/**
* Constraints:
* - 0 <= nums.length <= 105
* - -109 <= nums[i] <= 109
*
* Output
* - 가장 긴 길이
*
* 풀이 특이점
* - 둘다 시간복잡도는 O(N)으로 생각되는데 Runtime의 결과 차이가 꽤 크게 나온 점
*/

class Solution {
public int longestConsecutive(int[] nums) {
// (1) Set & num -1
// 시간복잡도 : O(N)
// Runtime : 1267ms Beats 5.15%
// Memory : 63.30MB Beats 62.58%
// Set<Integer> uniqueNums = Arrays.stream(nums).boxed().collect(Collectors.toSet());
// int result = 0;

// for (int num : nums) {
Copy link
Member

@dusunax dusunax Dec 9, 2024

Choose a reason for hiding this comment

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

시간 복잡도는 O(N)이지만
nums 배열을 순회하면서, 중복된 숫자 또한 계산하기 때문에 비효율적인 것 같습니다.

하단 코드블록처럼 uniqueNums을 순회하면 다음 결과가 나옵니다!

Runtime: 35ms Beats 49.03%
Memory: 63.20MB Beats 62.70%
 for (int num : uniqueNums) {
    if (uniqueNums.contains(num - 1)) continue;
    int currentNum = num;
    int currentLength = 1;
    
    while (uniqueNums.contains(currentNum + 1)) {
        currentNum++;
        currentLength++;
    }

    result = Math.max(result, currentLength);
}

Copy link
Contributor

Choose a reason for hiding this comment

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

@dusunax FYI) 코드 여러줄에 대한 개선안/대안 코드를 제시할 땐, 아래처럼 해주시면 더 좋을 것 같아요

  1. 여러 줄 드래그
  2. Add a suggestion 버튼 눌러서 코드 작성

Copy link
Contributor

Choose a reason for hiding this comment

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

예시 이미지..
image

image

// if (uniqueNums.contains(num - 1)) continue;
// int length = 1;
// while (uniqueNums.contains(num + length)) length += 1;
// result = Math.max(length, result);
// }

// return result;

// (2) HashMap
// 시간복잡도 : O(N)
// Runtime : 38ms Beats 46.54%
// Memory : 66.45MB Beats 51.28%
HashMap<Integer, Boolean> hm = new HashMap<>();

for(int i=0; i<nums.length; i++){
hm.put(nums[i], false);
}

for(int key : hm.keySet()){
if(hm.containsKey(key - 1)){
hm.put(key, true);
}
}

int max = 0;
for(int key : hm.keySet()){
int k =1;
if(hm.get(key)){
while(hm.containsKey(key + k)){
k++;
}
}

max = Math.max(max, k);
}

return max;
Comment on lines +31 to +59
Copy link
Contributor

Choose a reason for hiding this comment

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

이 풀이는 테스트 케이스를 통과하지 못하네요

Copy link
Contributor

Choose a reason for hiding this comment

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

1번 풀이에서는 for (int num : nums) { 반복문에서 처리하던 작업을 2번 풀이에서는 2, 3번 for문으로 나눠서 처리하신 것 같은데 특별한 의도가 있을까요? :)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

이 풀이는 테스트 케이스를 통과하지 못하네요

(2)번 풀이가 맞을까요?? 다시 시도해봤을 때는 제쪽에서 모두 통과되는 것으로 확인되었습니다!

1번 풀이에서는 for (int num : nums) { 반복문에서 처리하던 작업을 2번 풀이에서는 2, 3번 for문으로 나눠서 처리하신 것 같은데 특별한 의도가 있을까요? :)

1번 풀이는 for에서 nums를 순차적으로 체크해서 길이를 추출하지만, 2번 풀이에서는 for의 역할이

  1. hashmap 초기화
  2. 이전 키 존재여부 체크
  3. 이전 키 존재에 따른 길이 누적

를 처리하기 위해 for의 개수가 나뉘어졌다고 생각해주시면 될 것 같습니다!

}
}
82 changes: 82 additions & 0 deletions top-k-frequent-elements/kdh-92.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
* Constraints
* 1 <= nums.length <= 10^5
* -10^4 <= nums[i] <= 10^4
* k is in the range [1, the number of unique elements in the array].
* It is guaranteed that the answer is unique.
*
* Output
* - int 배열
*/

class Solution {
public int[] topKFrequent(int[] nums, int k) {
// (1) HashMap + PriorityQueue
// 시간복잡도 : O(N log N)
// Runtime : 15ms Beats 38.03%
// Memory : 48.93MB Beats 20.01%
Map<Integer, Integer> frequencyMap = new HashMap<>();

for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue));
Copy link
Member

@dusunax dusunax Dec 9, 2024

Choose a reason for hiding this comment

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

java에 PriorityQueue라는 우선순위 큐 클래스가 존재하는군요
덕분에 Heap 자료구조에 대해 자세히 조사해봤습니다

Copy link
Contributor

Choose a reason for hiding this comment

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

Heap 자료구조는 앞으로도 많이 쓰이는 자료구조이니 한 번 제대로 공부해두시길 추천합니다!

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Priority Queue의 Comparable & Comparator를 잘 사용하면 상당히 쉽게 해결할 수 있는 문제들이 있더라구요 :)
잘 공부해두면 도움이 많이 되는 것 같습니다!


for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) {
minHeap.offer(entry);
if (minHeap.size() > k) {
minHeap.poll();
}
}

int[] result = new int[k];

for (int i = 0; i < k; i++) {
result[i] = minHeap.poll().getKey();
}

return result;

// (2) Stream
// 시간복잡도 : O(N log N)
// Runtime : 19ms Beats 8.16%
// Memory : 49.00MB Beats 20.01%
// Stream에 익숙해지기 위해 공부용
return Arrays.stream(nums)
.boxed()
.collect(Collectors.groupingBy(num -> num, Collectors.summingInt(num -> 1)))
.entrySet().stream()
.sorted((a, b) -> b.getValue() - a.getValue())
.limit(k)
.mapToInt(Map.Entry::getKey)
.toArray();

// (3) Array List
// 시간복잡도 : O(N)
// Runtime : 13ms Beats 75.77%
// Memory : 48.44MB Beats 61.68%
Map<Integer, Integer> frequencyMap = new HashMap<>();
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

List<Integer>[] buckets = new List[nums.length + 1];
for (int key : frequencyMap.keySet()) {
int freq = frequencyMap.get(key);
if (buckets[freq] == null) {
buckets[freq] = new ArrayList<>();
}
buckets[freq].add(key);
}

List<Integer> result = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0 && result.size() < k; i--) {
if (buckets[i] != null) {
result.addAll(buckets[i]);
}
}

return result.stream().mapToInt(Integer::intValue).toArray();
}
}
65 changes: 65 additions & 0 deletions valid-palindrome/kdh-92.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Constraints
* - 1 <= s.length <= 2 * 10^5
* - s consists only of printable ASCII characters.
*
* Output
* - true : 좌우 동일
* - false : 좌우 비동일
*/


class Solution {
public boolean isPalindrome(String s) {

// 해결법 1 (투포인터)
// 시간복잡도: O(N), 공간 복잡도 : O(1)
Copy link
Member

Choose a reason for hiding this comment

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

👍

여러 방식으로 생각하면서 푸시는 것 같아서 저도 공부가 됩니다.
(1)이 효율적이고 (2)가 명확해보이네요

// 2ms & Beats 99.05%
int left = 0, right = s.length() - 1;

while (left < right) {
// (1)
if (!Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
else if (!Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
else {
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}

left++;
right--;
}


// (2)
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}

return true;

// 해결법 2 (Stream API)
// 시간 복잡도 : O(N), 공간 복잡도 : O(N)
// 133ms & Beats 5.58%
String filtered = s.chars()
.filter(Character::isLetterOrDigit)
.mapToObj(c -> String.valueOf((char) Character.toLowerCase(c)))
.reduce("", String::concat);
Copy link
Member

Choose a reason for hiding this comment

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

함수형으로 푸는 것도 좋은 방식 같습니다!

다만 .reduce("", String::concat)에서 내부의 String::concat가 O(n)이라
시간복잡도가 O(N^2)이 된다고 하네요

gpt에게 물어보니 StringBuilder를 사용하면 문자열 병합이 제자리에서 수행되어서 개선할 수 있다고 합니다

String filtered = s.chars()
    .filter(Character::isLetterOrDigit)
    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
    .toString();

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Stream 방식만 사용하는걸 생각했는데 String::concat이 시간복잡도 O(N^2)인 걸 놓쳤네요!
감사합니다! 👍


return IntStream.range(0, filtered.length() / 2)
.allMatch(i -> filtered.charAt(i) == filtered.charAt(filtered.length() - 1 - i));
}
}
Loading