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

[권동현] Week 1 #629

merged 6 commits into from
Dec 14, 2024

Conversation

kdh-92
Copy link
Contributor

@kdh-92 kdh-92 commented Dec 4, 2024

답안 제출 문제

체크 리스트

  • PR을 프로젝트에 추가하고 Week를 현재 주차로 설정해주세요.
  • 바로 앞에 PR을 열어주신 분을 코드 검토자로 지정해주세요.
  • 문제를 모두 푸시면 프로젝트에서 Status를 In Review로 설정해주세요.
  • 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요.

@kdh-92 kdh-92 requested a review from a team as a code owner December 4, 2024 10:08
@github-actions github-actions bot added the java label Dec 4, 2024
@kdh-92 kdh-92 marked this pull request as draft December 4, 2024 10:14
@kdh-92 kdh-92 marked this pull request as ready for review December 4, 2024 10:15
@kdh-92 kdh-92 closed this Dec 4, 2024
@kdh-92 kdh-92 requested a review from dusunax December 4, 2024 10:53
@kdh-92 kdh-92 reopened this Dec 4, 2024
Copy link
Member

@dusunax dusunax left a comment

Choose a reason for hiding this comment

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

동현님 안녕하세요!
저는 주로 JavaScript를 사용하고 있습니다. 잘 부탁드립니다🙂


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을 사용해봤습니다!

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)가 명확해보이네요

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)인 걸 놓쳤네요!
감사합니다! 👍

@kdh-92
Copy link
Contributor Author

kdh-92 commented Dec 5, 2024

@dusunax 선아님 안녕하세요 :)
저는 현재는 java를 주로 쓰고, 전에는 javascript를 주로 사용했습니다!
잘 부탁드립니다~!

@HC-kang
Copy link
Contributor

HC-kang commented Dec 9, 2024

@kdh-92 님 안녕하세요!
사용중인 filename check CI에 버그가 있었습니다. 이미 한번 수정을 시도하셨네요 😿
최신 변경사항을 반영한 뒤 다시 한 번 시도해 주시겠어요?
번거롭게 해 드려 죄송합니다!

@kdh-92
Copy link
Contributor Author

kdh-92 commented Dec 9, 2024

@kdh-92 님 안녕하세요! 사용중인 filename check CI에 버그가 있었습니다. 이미 한번 수정을 시도하셨네요 😿 최신 변경사항을 반영한 뒤 다시 한 번 시도해 주시겠어요? 번거롭게 해 드려 죄송합니다!

넵 :) 감사합니다!

Copy link
Member

@dusunax dusunax left a comment

Choose a reason for hiding this comment

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

최근에 js & python으로 푼 답안을 java로 옮겨적으면서 조금(아주 조금씩) 익혀가고 있는데
자바를 학습하신 분들의 코드가 많이 도움이 됩니다👍

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를 잘 사용하면 상당히 쉽게 해결할 수 있는 문제들이 있더라구요 :)
잘 공부해두면 도움이 많이 되는 것 같습니다!

// 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

Comment on lines +31 to +59
// (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;
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의 개수가 나뉘어졌다고 생각해주시면 될 것 같습니다!

@obzva
Copy link
Contributor

obzva commented Dec 10, 2024

전반적으로 같은 문제를 여러 방식으로 풀어보며 본인 것으로 만드려고 하시는 모습이 보기 좋았습니다
아래는 작은 피드백들입니다

  1. 어떤 풀이는 Big O 분석이 되어 있고, 또 어떤 풀이는 공간 복잡도 분석이 빠져 있습니다 ㅎㅎ 리트코드 submit 결과의 runtime/memory를 의식하기보다는 스스로 Big O 분석하는 연습을 하시는 걸 추천드립니다
  2. Java 언어를 모르면 알기 힘든 method들이 많이 쓰여 읽기 어렵다고 느껴졌습니다, 주석을 조금 곁들여주시면 리뷰어 입장에서 더 수월할 것 같습니다 :)

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까지 직접 눌러주세요~

@kdh-92
Copy link
Contributor Author

kdh-92 commented Dec 14, 2024

전반적으로 같은 문제를 여러 방식으로 풀어보며 본인 것으로 만드려고 하시는 모습이 보기 좋았습니다 아래는 작은 피드백들입니다

  1. 어떤 풀이는 Big O 분석이 되어 있고, 또 어떤 풀이는 공간 복잡도 분석이 빠져 있습니다 ㅎㅎ 리트코드 submit 결과의 runtime/memory를 의식하기보다는 스스로 Big O 분석하는 연습을 하시는 걸 추천드립니다
  2. Java 언어를 모르면 알기 힘든 method들이 많이 쓰여 읽기 어렵다고 느껴졌습니다, 주석을 조금 곁들여주시면 리뷰어 입장에서 더 수월할 것 같습니다 :)

말씀해주신것처럼 submit 후 runtime/memory를 보고 문제 풀기에만 집중하게 되었는데 반성하게 되네요!
좋은 피드백 주셔서 감사합니다 :)

2주차에는 method에 대해 좀 더 신경써서 작성해보겠습니다 :)

@kdh-92 kdh-92 merged commit 2cb2fc9 into DaleStudy:main Dec 14, 2024
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
No open projects
Status: Completed
Development

Successfully merging this pull request may close these issues.

4 participants