-
-
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
Changes from all commits
829d5a4
e09178a
f9c216c
e48bda1
4ac4481
324485e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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; | ||
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; | ||
} | ||
} |
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. LGTM👍 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} | ||
} |
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) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 시간 복잡도는 O(N)이지만 하단 코드블록처럼 uniqueNums을 순회하면 다음 결과가 나옵니다!
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 commentThe reason will be displayed to describe this comment to others. Learn more. @dusunax FYI) 코드 여러줄에 대한 개선안/대안 코드를 제시할 땐, 아래처럼 해주시면 더 좋을 것 같아요
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
// 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 commentThe reason will be displayed to describe this comment to others. Learn more. 1번 풀이에서는 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
(2)번 풀이가 맞을까요?? 다시 시도해봤을 때는 제쪽에서 모두 통과되는 것으로 확인되었습니다!
1번 풀이는 for에서 nums를 순차적으로 체크해서 길이를 추출하지만, 2번 풀이에서는 for의 역할이
를 처리하기 위해 for의 개수가 나뉘어졌다고 생각해주시면 될 것 같습니다! |
||
} | ||
} |
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)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. java에 PriorityQueue라는 우선순위 큐 클래스가 존재하는군요 There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 commentThe 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(); | ||
} | ||
} |
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) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 👍 여러 방식으로 생각하면서 푸시는 것 같아서 저도 공부가 됩니다. |
||
// 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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 함수형으로 푸는 것도 좋은 방식 같습니다! 다만 .reduce("", String::concat)에서 내부의 String::concat가 O(n)이라 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 commentThe 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)); | ||
} | ||
} |
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 성능
(생각보다는 차이가 있네요!?)
추가로 코테를 풀면서 getOrDefault를 사용하게 되는 경우가 많더라구요!
이전에 문제 푸는 과정에서 해당 메서드 이름이 생각이 안 나서 고생했던 적이 있어 익숙해지고 싶어 HashMap을 사용해봤습니다!