-
-
Notifications
You must be signed in to change notification settings - Fork 195
[권동현] 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
[권동현] Week 1 #629
Conversation
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.
동현님 안녕하세요!
저는 주로 JavaScript를 사용하고 있습니다. 잘 부탁드립니다🙂
|
||
for (int num: nums) { | ||
int count = countMap.getOrDefault(num, 0) + 1; | ||
if (count > 1) return true; |
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.
자바 Map에는 getOrDefault이라는 메소드가 있군요!
질문이 있는데 혹시 HashSet add 메소드의 반환값 boolean을 사용하는 게 아니라 HashMap을 사용하신 이유가 있나요?
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.
위 문제 관련해서는 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) |
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.
👍
여러 방식으로 생각하면서 푸시는 것 같아서 저도 공부가 됩니다.
(1)이 효율적이고 (2)가 명확해보이네요
String filtered = s.chars() | ||
.filter(Character::isLetterOrDigit) | ||
.mapToObj(c -> String.valueOf((char) Character.toLowerCase(c))) | ||
.reduce("", String::concat); |
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.
함수형으로 푸는 것도 좋은 방식 같습니다!
다만 .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();
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.
Stream 방식만 사용하는걸 생각했는데 String::concat이 시간복잡도 O(N^2)인 걸 놓쳤네요!
감사합니다! 👍
@dusunax 선아님 안녕하세요 :) |
@kdh-92 님 안녕하세요! |
넵 :) 감사합니다! |
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.
최근에 js & python으로 푼 답안을 java로 옮겨적으면서 조금(아주 조금씩) 익혀가고 있는데
자바를 학습하신 분들의 코드가 많이 도움이 됩니다👍
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); | ||
} | ||
|
||
PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue)); |
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.
java에 PriorityQueue라는 우선순위 큐 클래스가 존재하는군요
덕분에 Heap 자료구조에 대해 자세히 조사해봤습니다
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.
Heap 자료구조는 앞으로도 많이 쓰이는 자료구조이니 한 번 제대로 공부해두시길 추천합니다!
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.
Priority Queue의 Comparable & Comparator를 잘 사용하면 상당히 쉽게 해결할 수 있는 문제들이 있더라구요 :)
잘 공부해두면 도움이 많이 되는 것 같습니다!
// Set<Integer> uniqueNums = Arrays.stream(nums).boxed().collect(Collectors.toSet()); | ||
// int result = 0; | ||
|
||
// for (int num : nums) { |
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.
시간 복잡도는 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);
}
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.
@dusunax FYI) 코드 여러줄에 대한 개선안/대안 코드를 제시할 땐, 아래처럼 해주시면 더 좋을 것 같아요
- 여러 줄 드래그
- Add a suggestion 버튼 눌러서 코드 작성
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.
// (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; |
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.
이 풀이는 테스트 케이스를 통과하지 못하네요
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.
1번 풀이에서는 for (int num : nums) {
반복문에서 처리하던 작업을 2번 풀이에서는 2, 3번 for문으로 나눠서 처리하신 것 같은데 특별한 의도가 있을까요? :)
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.
이 풀이는 테스트 케이스를 통과하지 못하네요
(2)번 풀이가 맞을까요?? 다시 시도해봤을 때는 제쪽에서 모두 통과되는 것으로 확인되었습니다!
1번 풀이에서는 for (int num : nums) { 반복문에서 처리하던 작업을 2번 풀이에서는 2, 3번 for문으로 나눠서 처리하신 것 같은데 특별한 의도가 있을까요? :)
1번 풀이는 for에서 nums를 순차적으로 체크해서 길이를 추출하지만, 2번 풀이에서는 for의 역할이
- hashmap 초기화
- 이전 키 존재여부 체크
- 이전 키 존재에 따른 길이 누적
를 처리하기 위해 for의 개수가 나뉘어졌다고 생각해주시면 될 것 같습니다!
전반적으로 같은 문제를 여러 방식으로 풀어보며 본인 것으로 만드려고 하시는 모습이 보기 좋았습니다
|
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.
LGTM👍
저는 dp로만 풀이했는데 두 번째 방식도 배워갑니다
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.
@dusunax 보시기에 approve해도 괜찮겠다 싶으시면 approve까지 직접 눌러주세요~
말씀해주신것처럼 submit 후 runtime/memory를 보고 문제 풀기에만 집중하게 되었는데 반성하게 되네요! 2주차에는 method에 대해 좀 더 신경써서 작성해보겠습니다 :) |
답안 제출 문제
체크 리스트
In Review
로 설정해주세요.