-
-
Notifications
You must be signed in to change notification settings - Fork 271
[ys-han00] WEEK 01 solutions #1973
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
base: main
Are you sure you want to change the base?
Changes from all commits
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,37 @@ | ||
| #include <bits/stdc++.h> | ||
|
|
||
| class Solution { | ||
| public: | ||
| bool containsDuplicate(vector<int>& nums) { | ||
| sort(nums.begin(), nums.end()); | ||
|
|
||
| for(int i = 0; i < nums.size() - 1; i++) | ||
| if(nums[i] == nums[i+1]) | ||
| return true; | ||
|
|
||
| return false; | ||
| } | ||
| }; | ||
|
|
||
| // 첫 시도 및 틀린 풀이 | ||
| // 틀린 이유: | ||
| // leetcode는 처음 풀어보는데, 백준보다 시간 제한이 엄격함 | ||
| // -> 20억 배열 선언하는것만으로도 시간초과 발생 | ||
| // | ||
| // class Solution { | ||
| // public: | ||
| // bool containsDuplicate(vector<int>& nums) { | ||
| // vector<bool> check(2'000'000'001, false); | ||
| // int offset = 1'000'000'000; | ||
|
|
||
| // for(int i = 0; i < nums.size(); i++) { | ||
| // int idx = nums[i] + offset; | ||
|
|
||
| // if(check[idx] == true) | ||
| // return true; | ||
| // check[idx] = 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. 와우..! 이 문제가 DP로도 풀 수 있었군요! 💪 저는 DFS를 통해서 풀었는데, 새로운 접근법 배워갑니다 👍 |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| class Solution { | ||
| public: | ||
| int rob(vector<int>& nums) { | ||
| vector<int> dp(nums.size(), 0); | ||
|
|
||
| dp[0] = nums[0]; | ||
| if(dp.size() == 1) | ||
| return dp[0]; | ||
|
|
||
| dp[1] = nums[1]; | ||
| int ans = max(dp[0], dp[1]); | ||
|
|
||
| for(int i = 2; i < dp.size(); i++) { | ||
| int maxi = -1; | ||
| for(int j = 0; j < i - 1; j++) | ||
| maxi = max(dp[j], maxi); | ||
| dp[i] = maxi + nums[i]; | ||
| ans = max(ans, dp[i]); | ||
| } | ||
|
|
||
| return ans; | ||
| } | ||
| }; | ||
|
|
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| #include <bits/stdc++.h> | ||
|
|
||
| class Solution { | ||
| public: | ||
| int longestConsecutive(vector<int>& nums) { | ||
| if(nums.size() == 0) | ||
| return 0; | ||
|
|
||
| sort(nums.begin(), nums.end()); | ||
|
|
||
| int ans = 1, cnt = 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.
만약 그렇다면 변수명을 조금 더 명확하게 하면 의도가 더 잘 드러나는 코드가 될 것 같아요!
Author
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.
이것도 알고리즘 풀 때 있는 습관이네요... 고쳐야 할 습관이 많네요 여태까지는 혼자 알고리즘 풀고 맞추면 끝이었는데, 이번 스터디에서는 다른 분들과 공유한다는 점을 참고해서 싹 고쳐봐야겠습니다! 의견 감사합니다. |
||
| for(int i = 1; i < nums.size(); i++) { | ||
| if(nums[i] == nums[i - 1]) | ||
| continue; | ||
| if(nums[i] - 1 == nums[i - 1]) | ||
| cnt++; | ||
|
Comment on lines
+13
to
+16
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.
아래와 같이 임시 변수로 빼서 처리하는 방법도 있을 것 같은데, 어떠신가요? int current = nums[i]
int previous = nums[i-1]
if(current == previous) {
...
}
if (current == previous + 1) {
current_length ++;
}이렇게 하면
작은 차이지만 가독성 측면에서 좋을 것 같아서 제안드려봐요 👍
Author
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.
숏코딩하려는 습관이 하하. 의견 감사해요! |
||
| else | ||
| cnt = 1; | ||
| ans = max(cnt, ans); | ||
| } | ||
|
|
||
| return ans; | ||
| } | ||
| }; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| #include <bits/stdc++.h> | ||
|
|
||
| class Solution { | ||
| public: | ||
| vector<int> topKFrequent(vector<int>& nums, int k) { | ||
| map<int, int> count; | ||
|
|
||
| for(int i = 0; i < nums.size(); i++) { | ||
| if(count.find(nums[i]) == count.end()) | ||
| count[nums[i]] = 1; | ||
| else | ||
| count[nums[i]]++; | ||
|
Comment on lines
+9
to
+12
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. [단순 궁금] 제가 잘 몰라서 질문드려요! C++ python에서는 Key가 없으면 자동으로 0으로 초기화할 수 있는 방법이 있어서 ㅎㅎ 이게 가능하면 for(int i = 0; i < num.size(); i++) {
count[num[i]]++;
}
Author
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. 여태까지 python 이번 기회에 비효율적이게 쓰던 코드들 한번 고쳐봐야겠어요! 정말 좋은 팁 감사합니다!! |
||
| } | ||
|
|
||
| vector<pair<int, int>> cnt(count.begin(), count.end()); | ||
| sort(cnt.begin(), cnt.end(), cmp); | ||
|
|
||
| vector<int> ans; | ||
| for(int i = 0; i < k; i++) | ||
| ans.push_back(cnt[i].first); | ||
|
|
||
| return ans; | ||
| } | ||
|
|
||
| static bool cmp(const pair<int, int>& a, const pair<int, int>& b) { | ||
| return a.second > b.second; | ||
| } | ||
| }; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| #include <bits/stdc++.h> | ||
|
|
||
| class Solution { | ||
| public: | ||
| vector<int> twoSum(vector<int>& nums, int target) { | ||
| vector<pair<int, int>> num_idx; | ||
| for(int i = 0; i < nums.size(); i++) | ||
| num_idx.push_back({nums[i], i}); | ||
|
|
||
| sort(num_idx.begin(), num_idx.end()); | ||
|
|
||
| int left = 0, right = nums.size() - 1; | ||
| while(1) { | ||
| if (num_idx[left].first + num_idx[right].first == target) | ||
| return vector<int>({num_idx[left].second, num_idx[right].second}); | ||
| if(num_idx[left].first + num_idx[right].first < target) left++; | ||
| else right--; | ||
| } | ||
| } | ||
| }; | ||
|
|
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.
아래와 같은 로직으로 이해했는데 제가 잘 이해한것이 맞을까요?
nums를 정렬한 다음로직이 명확하고 직관적이네요 👍
💡 참고: 다른 접근 방법
주석으로 남겨주신 첫 시도를 보니 이미 해싱 아이디어를 생각하셨던 것 같아요.
다만 배열 대신
unordered_set을 활용하면 시간과 메모리 문제를 해결할 수 있을 것 같아요!unordered_set을 이용하면 실제 등장한 숫자만 저장하기 때문에 메모리 효율적으로 동작할 수 있을 것 같아요.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.
네 맞게 이해하셨습니다! 간단하면서도 시간효율이 제일 좋아서 채택한 풀이입니다.
코드에는 포함되지 않았지만, 말씀하신
unordered_set을 사용해서도 풀어봤습니다. 예상하신대로 문제 없이 동작합니다! 하지만, 시간, 메모리 효율이 제출한 코드 보다 좋지 않아 코드에 포함하지 않았습니다 ㅎㅎ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.
이미
unordered_set을 이용해서 풀어보셨군요! 👍sort방식은 O(n logn) 방식이고unordered_set방식이 O(n)이라서 더 빠를 것 같았는데 실제로는 시간, 메모리 효율이 더 안좋았군요 🤔리트코드 테스트 케이스에 중복이 없거나 중복이 배열 끝부분에 있는 경우가 많으면 Sort가 더 빠르게 동작했을 것 같아요 ㅎㅎ
궁금해서 Claude한테 벤치마킹을 시켜봤는데 아래와 같이 나왔어요 ㅎㅎ 재미있네요 💪
참고하면 도움될듯하여 공유드려요!
테스트 환경
🔹 시나리오 1: 중복이 있는 경우 (Early Exit 가능)
→ 중복을 일찍 발견할 수 있으면 Hash가 압도적으로 빠름
🔹 시나리오 2: 중복이 없는 경우 (Worst Case - 전체 스캔)
→ 끝까지 스캔해야 하는 경우 Sort가 2~3배 빠름