From a48c32e01ed01d44332123b3762def53e528b413 Mon Sep 17 00:00:00 2001 From: csucom Date: Sun, 24 Nov 2024 22:40:24 +0900 Subject: [PATCH 001/396] add sample code for testing --- 3sum/csucom.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 3sum/csucom.py diff --git a/3sum/csucom.py b/3sum/csucom.py new file mode 100644 index 000000000..9def7cf98 --- /dev/null +++ b/3sum/csucom.py @@ -0,0 +1,3 @@ +''' + test code +''' \ No newline at end of file From f69468c645abdf1dfb7d354a545933f31b47852e Mon Sep 17 00:00:00 2001 From: Yoon Kim Date: Mon, 2 Dec 2024 22:17:50 -0800 Subject: [PATCH 002/396] contains duplicates solution --- contains-duplicate/yoonthecoder.js | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 contains-duplicate/yoonthecoder.js diff --git a/contains-duplicate/yoonthecoder.js b/contains-duplicate/yoonthecoder.js new file mode 100644 index 000000000..8de1552a8 --- /dev/null +++ b/contains-duplicate/yoonthecoder.js @@ -0,0 +1,10 @@ +var containsDuplicate = function (nums) { + // Create a set from the nums array. Since Sets only allow unique values, any duplicates will be removed. + const set = new Set(nums); + // Compare the size of the set and the length of the original array.- if the size of the set is smaller than the length of the original array('nums'), it means there were duplicates. + + return set.size < nums.length; +}; + +// Time Complexity: O(n); - adding elements to the Set & compare sizes +// Space Complexity: O(n) From ff2824325dcee41f2ce40253e5b25a0294682a14 Mon Sep 17 00:00:00 2001 From: Gotprgmer Date: Tue, 3 Dec 2024 17:54:37 +0900 Subject: [PATCH 003/396] add solution: Contains Duplicate --- contains-duplicate/Gotprgmer.java | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 contains-duplicate/Gotprgmer.java diff --git a/contains-duplicate/Gotprgmer.java b/contains-duplicate/Gotprgmer.java new file mode 100644 index 000000000..c48142186 --- /dev/null +++ b/contains-duplicate/Gotprgmer.java @@ -0,0 +1,33 @@ +import java.util.*; +class SolutionGotprgmer { + // 해당 문제는 어느 한 숫자가 2개이상 존재할 경우 true를 그렇지 않을 경우, false를 반환하는 문제이다. + // set을 사용해서 set에 이미 값이 존재한다면 개수가 2 이상이므로 true 그렇지 않으면 false를 출력한다. + + // 각 숫자들을 저장해서 set으로 관리 -> distinctNums + // nums의 각 숫자인 checkNum을 distinctNums에 넣어준다. + // 만약 checkNum이 이미 distinctNums에 존재한다면 ans를 true로 만들어주고 답을 출력한다. + + + // 시간복잡도 -> O(n) + // 공간복잡도 -> O(n) + static Set distinctNums; + public boolean containsDuplicate(int[] nums) { + distinctNums = new HashSet<>(); + boolean ans = false; + for(int checkNum:nums){ + if(distinctNums.contains(checkNum)){ + ans = true; + break; + }; + distinctNums.add(checkNum); + } + return ans; + } + public static void main(String[] args){ + Solution s = new Solution(); + System.out.println(s); + + } + + +} \ No newline at end of file From 767db548f8b3ef5246d5d42f49bb4c6fe227e86e Mon Sep 17 00:00:00 2001 From: Gotprgmer Date: Tue, 3 Dec 2024 18:52:15 +0900 Subject: [PATCH 004/396] =?UTF-8?q?fix=20solution:=20Contains=20Duplicate?= =?UTF-8?q?=20(=EB=A7=88=EC=A7=80=EB=A7=89=20=EC=A4=84=EB=B0=94=EA=BF=88?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80,=20main=EB=A9=94=EC=84=9C=EB=93=9C=20?= =?UTF-8?q?=EC=82=AD=EC=A0=9C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/Gotprgmer.java | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/contains-duplicate/Gotprgmer.java b/contains-duplicate/Gotprgmer.java index c48142186..a6d535dc9 100644 --- a/contains-duplicate/Gotprgmer.java +++ b/contains-duplicate/Gotprgmer.java @@ -1,4 +1,6 @@ -import java.util.*; +import java.util.HashSet; +import java.util.Set; + class SolutionGotprgmer { // 해당 문제는 어느 한 숫자가 2개이상 존재할 경우 true를 그렇지 않을 경우, false를 반환하는 문제이다. // set을 사용해서 set에 이미 값이 존재한다면 개수가 2 이상이므로 true 그렇지 않으면 false를 출력한다. @@ -14,8 +16,8 @@ class SolutionGotprgmer { public boolean containsDuplicate(int[] nums) { distinctNums = new HashSet<>(); boolean ans = false; - for(int checkNum:nums){ - if(distinctNums.contains(checkNum)){ + for (int checkNum : nums) { + if (distinctNums.contains(checkNum)) { ans = true; break; }; @@ -23,11 +25,6 @@ public boolean containsDuplicate(int[] nums) { } return ans; } - public static void main(String[] args){ - Solution s = new Solution(); - System.out.println(s); - - } -} \ No newline at end of file +} From 7796f75094925d77686f9421185d591d2e1b8ee1 Mon Sep 17 00:00:00 2001 From: Gotprgmer Date: Tue, 3 Dec 2024 19:14:28 +0900 Subject: [PATCH 005/396] add solution: Valid Palindrome --- valid-palindrome/Gotprgmer.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 valid-palindrome/Gotprgmer.java diff --git a/valid-palindrome/Gotprgmer.java b/valid-palindrome/Gotprgmer.java new file mode 100644 index 000000000..64cd1e2a5 --- /dev/null +++ b/valid-palindrome/Gotprgmer.java @@ -0,0 +1,31 @@ +// 입력된 문자 중 알파벳이나 숫자가 아닌 값들을 하나의 문자열로 만든다. +// 이때 모든 문자들을 소문자로 바꾼다. +// 역정렬한 값과 원래 값을 비교해 팰린드롬 유무를 출력한다. + +// 알파벳 혹은 숫자가 아닌지 검사하는 문자 -> charToCheck + +// 시간복잡도 : O(n) +// 공간복잡도 : O(n) + +class Solution_Gotprgmer { + static StringBuilder sb; + public boolean isPalindrome(String s) { + sb = new StringBuilder(); + for(char charToCheck : s.toCharArray()){ + if(!Character.isLetterOrDigit(charToCheck)){ + continue; + } + sb.append(Character.toLowerCase(charToCheck)); + } + String originalDirection = sb.toString(); + String reDirection = sb.reverse().toString(); + + if(originalDirection.equals(reDirection)){ + + return true; + } + else{ + return false; + } + } +} From 1dd6829bb7b6cb01433b09838240deb96f670843 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 3 Dec 2024 20:57:31 +0900 Subject: [PATCH 006/396] feat: [WEEK1-1] solve contains-duplicate --- contains-duplicate/Chaedie.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 contains-duplicate/Chaedie.py diff --git a/contains-duplicate/Chaedie.py b/contains-duplicate/Chaedie.py new file mode 100644 index 000000000..822394382 --- /dev/null +++ b/contains-duplicate/Chaedie.py @@ -0,0 +1,21 @@ + + +''' +풀이: + 중복된 요소가 있는지 찾는 문제입니다. + + hash set 으로 중복을 제거하고 + 기존 nums 의 길이와 중복 제거된 nums_set 의 길이가 같은지 return 했습니다. + +시간 복잡도: + O(n) - has set 을 만드는 시간 + +공간 복잡도: + O(n) - n개의 요소를 set에 담기 때문 +''' + + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + nums_set = set(nums) + return len(nums_set) != len(nums) From cafc2981e34a82ecd4d7692017d09d0b11bcbd2c Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 22:00:02 +0900 Subject: [PATCH 007/396] feat: contains-duplicate --- contains-duplicate/changchanghwang.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 contains-duplicate/changchanghwang.go diff --git a/contains-duplicate/changchanghwang.go b/contains-duplicate/changchanghwang.go new file mode 100644 index 000000000..3718ad5b5 --- /dev/null +++ b/contains-duplicate/changchanghwang.go @@ -0,0 +1,13 @@ +// Time complexity, O(n) +// Space complexity, O(n) +func containsDuplicate(nums []int) bool { + hashMap := map[int]bool{} + for _, num := range nums { + if hashMap[num] { + return true + } else { + hashMap[num] = true + } + } + return false +} \ No newline at end of file From 380ee0cfff180033c3cf5dd12ba6174fbb6a38b9 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 22:03:33 +0900 Subject: [PATCH 008/396] feat: valid-palindrome --- valid-palindrome/changchanghwang.go | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 valid-palindrome/changchanghwang.go diff --git a/valid-palindrome/changchanghwang.go b/valid-palindrome/changchanghwang.go new file mode 100644 index 000000000..5961c63a3 --- /dev/null +++ b/valid-palindrome/changchanghwang.go @@ -0,0 +1,34 @@ +// O(n) time complexity +// O(n) space complexity +func isPalindrome(s string) bool { + regex, _ := regexp.Compile("[a-zA-Z0-9]") + reverseAndFilteredString := "" + filteredString := "" + + for _, char := range s { + if regex.MatchString(string(char)) { + c := strings.ToLower(string(char)) + reverseAndFilteredString = c + reverseAndFilteredString + filteredString += c + } + } + + return reverseAndFilteredString == filteredString +} + +// O(n) time complexity +// O(n) space complexity +func isPalindrome2(s string) bool { + reverseAndFilteredString := "" + filteredString := "" + + for _, char := range s { + if unicode.IsLetter(char) || unicode.IsDigit(char) { + c := strings.ToLower(string(char)) + reverseAndFilteredString = c + reverseAndFilteredString + filteredString += c + } + } + + return reverseAndFilteredString == filteredString +} \ No newline at end of file From 2897867a2f8ad3e19c0bccdf1e8da20eee6da565 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 22:07:18 +0900 Subject: [PATCH 009/396] feat: top-k-frequent-elements --- top-k-frequent-elements/changchanghwang.go | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 top-k-frequent-elements/changchanghwang.go diff --git a/top-k-frequent-elements/changchanghwang.go b/top-k-frequent-elements/changchanghwang.go new file mode 100644 index 000000000..301784998 --- /dev/null +++ b/top-k-frequent-elements/changchanghwang.go @@ -0,0 +1,25 @@ +// Time: O(nlogn) +// Space: O(n) +func topKFrequent(nums []int, k int) []int { + hashMap := map[int]int{} + for _, num := range nums { + hashMap[num]++ + } + + result := [][]int{} + + for key, value := range hashMap { + result = append(result, []int{key, value}) + } + + sort.Slice(result, func(i, j int) bool { // go의 sort는 quicksort를 기본적으로 사용한다. O(nlogn) + return result[i][1] > result[j][1] + }) + + resultNums := []int{} + for i := 0; i < k; i++ { + resultNums = append(resultNums, result[i][0]) + } + + return resultNums[:k] +} From 164b56b76d2f41b4b9b3f760a5159ad883f67883 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 22:09:14 +0900 Subject: [PATCH 010/396] chore: rename variable, add comment --- top-k-frequent-elements/changchanghwang.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/top-k-frequent-elements/changchanghwang.go b/top-k-frequent-elements/changchanghwang.go index 301784998..3684a74a2 100644 --- a/top-k-frequent-elements/changchanghwang.go +++ b/top-k-frequent-elements/changchanghwang.go @@ -8,8 +8,8 @@ func topKFrequent(nums []int, k int) []int { result := [][]int{} - for key, value := range hashMap { - result = append(result, []int{key, value}) + for num, count := range hashMap { + result = append(result, []int{num, count}) } sort.Slice(result, func(i, j int) bool { // go의 sort는 quicksort를 기본적으로 사용한다. O(nlogn) @@ -18,7 +18,7 @@ func topKFrequent(nums []int, k int) []int { resultNums := []int{} for i := 0; i < k; i++ { - resultNums = append(resultNums, result[i][0]) + resultNums = append(resultNums, result[i][0]) // 정렬을 했기 때문에 앞에서부터 k개만 뽑아내면 된다. } return resultNums[:k] From 50a44288e2d23dedf1f83918e7695ed2b37c8816 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 22:13:10 +0900 Subject: [PATCH 011/396] chore: solution comment --- contains-duplicate/changchanghwang.go | 3 +++ top-k-frequent-elements/changchanghwang.go | 4 ++++ valid-palindrome/changchanghwang.go | 3 +++ 3 files changed, 10 insertions(+) diff --git a/contains-duplicate/changchanghwang.go b/contains-duplicate/changchanghwang.go index 3718ad5b5..aaf425fe6 100644 --- a/contains-duplicate/changchanghwang.go +++ b/contains-duplicate/changchanghwang.go @@ -1,5 +1,8 @@ // Time complexity, O(n) // Space complexity, O(n) +// 풀이 +// nums 배열을 순회하면서 hashMap에 num을 key로, 존재 여부를 value로 저장한다. +// 만약 이미 존재하는 key라면 true를 반환하고, 순회를 전부 했는데도 중복이 없다면 false를 반환한다. func containsDuplicate(nums []int) bool { hashMap := map[int]bool{} for _, num := range nums { diff --git a/top-k-frequent-elements/changchanghwang.go b/top-k-frequent-elements/changchanghwang.go index 3684a74a2..625a60308 100644 --- a/top-k-frequent-elements/changchanghwang.go +++ b/top-k-frequent-elements/changchanghwang.go @@ -1,5 +1,9 @@ // Time: O(nlogn) // Space: O(n) +// 풀이 +// hashMap에 num을 key로, count를 value로 저장한다. +// hashMap을 배열로 만들어 count순으로 정렬한다. +// 정렬된 배열에서 앞에서부터 k개만 뽑아내서 반환한다. func topKFrequent(nums []int, k int) []int { hashMap := map[int]int{} for _, num := range nums { diff --git a/valid-palindrome/changchanghwang.go b/valid-palindrome/changchanghwang.go index 5961c63a3..54dbe9aef 100644 --- a/valid-palindrome/changchanghwang.go +++ b/valid-palindrome/changchanghwang.go @@ -1,3 +1,6 @@ +// 풀이 +// alphabet, number만 걸러내서 소문자로 바꾼 후 reverse한 문자열, 걸러낸 문자열과 비교하여 같은지 확인한다. + // O(n) time complexity // O(n) space complexity func isPalindrome(s string) bool { From 23046df26ff2b1ac1d9f91cb5fc7ed22a3de5283 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 22:37:45 +0900 Subject: [PATCH 012/396] feat: longestConsecutive --- .../changchanghwang.go | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 longest-consecutive-sequence/changchanghwang.go diff --git a/longest-consecutive-sequence/changchanghwang.go b/longest-consecutive-sequence/changchanghwang.go new file mode 100644 index 000000000..e38c23db1 --- /dev/null +++ b/longest-consecutive-sequence/changchanghwang.go @@ -0,0 +1,34 @@ +// time complexity: O(n) +// space complexity: O(n) +// 풀이 +// 1. map에 nums의 모든 요소를 저장한다. +// 2. map을 순회하면서 num-1이 존재하는지 확인한다. +// 3. num-1이 존재하면 continue +// 4. num-1이 존재하지 않으면 consecutiveCount를 1로 초기화하고 num+1이 존재하는지 (연속적으로 숫자가 증가하는게 있는지) 확인한다. +// 5. num+1이 존재하면 consecutiveCount를 1 증가시키고 num을 1 증가시켜 다음 수를 찾는다. +// 6. num+1이 존재하지 않으면 현재까지의 consecutiveCount와 maxConsecutiveCount를 비교하여 maxConsecutiveCount를 갱신한다. +func longestConsecutive(nums []int) int { + numMap := make(map[int]bool) + + for _, num := range nums { + numMap[num] = true + } + + maxConsecutiveCount := 0 + + for num := range numMap { + if numMap[num-1] { + continue + } + consecutiveCount := 1 + for numMap[num+1] { + num++ + consecutiveCount++ + } + if consecutiveCount > maxConsecutiveCount { + maxConsecutiveCount = consecutiveCount + } + } + + return maxConsecutiveCount +} \ No newline at end of file From 0e529e585b2e6301bc4020d40b19a23507cd613b Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 23:31:52 +0900 Subject: [PATCH 013/396] fix: newline --- contains-duplicate/changchanghwang.go | 2 +- longest-consecutive-sequence/changchanghwang.go | 2 +- valid-palindrome/changchanghwang.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contains-duplicate/changchanghwang.go b/contains-duplicate/changchanghwang.go index aaf425fe6..efa330024 100644 --- a/contains-duplicate/changchanghwang.go +++ b/contains-duplicate/changchanghwang.go @@ -13,4 +13,4 @@ func containsDuplicate(nums []int) bool { } } return false -} \ No newline at end of file +} diff --git a/longest-consecutive-sequence/changchanghwang.go b/longest-consecutive-sequence/changchanghwang.go index e38c23db1..432f30b2c 100644 --- a/longest-consecutive-sequence/changchanghwang.go +++ b/longest-consecutive-sequence/changchanghwang.go @@ -31,4 +31,4 @@ func longestConsecutive(nums []int) int { } return maxConsecutiveCount -} \ No newline at end of file +} diff --git a/valid-palindrome/changchanghwang.go b/valid-palindrome/changchanghwang.go index 54dbe9aef..723fe6005 100644 --- a/valid-palindrome/changchanghwang.go +++ b/valid-palindrome/changchanghwang.go @@ -34,4 +34,4 @@ func isPalindrome2(s string) bool { } return reverseAndFilteredString == filteredString -} \ No newline at end of file +} From 3e77e09c567981e4daa92762477bc9e431663107 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 23:35:22 +0900 Subject: [PATCH 014/396] fix: slice limit cap --- top-k-frequent-elements/changchanghwang.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/top-k-frequent-elements/changchanghwang.go b/top-k-frequent-elements/changchanghwang.go index 625a60308..ae35d45fd 100644 --- a/top-k-frequent-elements/changchanghwang.go +++ b/top-k-frequent-elements/changchanghwang.go @@ -20,10 +20,10 @@ func topKFrequent(nums []int, k int) []int { return result[i][1] > result[j][1] }) - resultNums := []int{} + resultNums := make([]int, 0, k) for i := 0; i < k; i++ { - resultNums = append(resultNums, result[i][0]) // 정렬을 했기 때문에 앞에서부터 k개만 뽑아내면 된다. + resultNums = append(resultNums, result[i][0]) } - return resultNums[:k] + return resultNums } From a0ec37f2a3d164831dee152de2a3406cd8994694 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 23:42:50 +0900 Subject: [PATCH 015/396] fix: lowercase all better than lowercase each --- valid-palindrome/changchanghwang.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/valid-palindrome/changchanghwang.go b/valid-palindrome/changchanghwang.go index 723fe6005..af7f90ac9 100644 --- a/valid-palindrome/changchanghwang.go +++ b/valid-palindrome/changchanghwang.go @@ -5,12 +5,13 @@ // O(n) space complexity func isPalindrome(s string) bool { regex, _ := regexp.Compile("[a-zA-Z0-9]") + + lowerCaseString := strings.ToLower(s) reverseAndFilteredString := "" filteredString := "" - for _, char := range s { + for _, char := range lowerCaseString { if regex.MatchString(string(char)) { - c := strings.ToLower(string(char)) reverseAndFilteredString = c + reverseAndFilteredString filteredString += c } @@ -22,12 +23,12 @@ func isPalindrome(s string) bool { // O(n) time complexity // O(n) space complexity func isPalindrome2(s string) bool { + lowerCaseString := strings.ToLower(s) reverseAndFilteredString := "" filteredString := "" - for _, char := range s { + for _, char := range lowerCaseString { if unicode.IsLetter(char) || unicode.IsDigit(char) { - c := strings.ToLower(string(char)) reverseAndFilteredString = c + reverseAndFilteredString filteredString += c } From 01d2055fac93c83586230df07a3a8379f927a5cc Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Tue, 3 Dec 2024 23:53:17 +0900 Subject: [PATCH 016/396] fix: use strings builder --- valid-palindrome/changchanghwang.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/valid-palindrome/changchanghwang.go b/valid-palindrome/changchanghwang.go index af7f90ac9..ea234ebf8 100644 --- a/valid-palindrome/changchanghwang.go +++ b/valid-palindrome/changchanghwang.go @@ -25,14 +25,14 @@ func isPalindrome(s string) bool { func isPalindrome2(s string) bool { lowerCaseString := strings.ToLower(s) reverseAndFilteredString := "" - filteredString := "" + var filteredString strings.Builder for _, char := range lowerCaseString { if unicode.IsLetter(char) || unicode.IsDigit(char) { - reverseAndFilteredString = c + reverseAndFilteredString - filteredString += c + reverseAndFilteredString = string(char) + reverseAndFilteredString + filteredString.WriteRune(char) } } - return reverseAndFilteredString == filteredString + return reverseAndFilteredString == filteredString.String() } From f863f0352f92f3ebd8e2f0b55751b883c5b04a6a Mon Sep 17 00:00:00 2001 From: Yoon Kim Date: Tue, 3 Dec 2024 23:00:21 -0800 Subject: [PATCH 017/396] valid palindrome solution --- valid-palindrome/yoonthecoder.js | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 valid-palindrome/yoonthecoder.js diff --git a/valid-palindrome/yoonthecoder.js b/valid-palindrome/yoonthecoder.js new file mode 100644 index 000000000..cbd8685f8 --- /dev/null +++ b/valid-palindrome/yoonthecoder.js @@ -0,0 +1,11 @@ +var isPalindrome = function (s) { + // remove any special characters and space from the string + const formattedString = s.toLowerCase().replace(/[^a-zA-Z0-9]/g, ''); + // use split() method to separate each charaters and put them in an array - reverse it - concatenate + const reversedString = formattedString.split('').reverse().join(''); + + return reversedString === formattedString; +}; + +// time complexity: O(n) +// space complexity: O(n) From 3fdc206e755131d05df61c19b34dabda626cc9c2 Mon Sep 17 00:00:00 2001 From: hanseulhee <3021062@gmail.com> Date: Wed, 4 Dec 2024 17:12:46 +0900 Subject: [PATCH 018/396] contains duplicate solution --- contains-duplicate/hanseulhee.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 contains-duplicate/hanseulhee.js diff --git a/contains-duplicate/hanseulhee.js b/contains-duplicate/hanseulhee.js new file mode 100644 index 000000000..3147ca063 --- /dev/null +++ b/contains-duplicate/hanseulhee.js @@ -0,0 +1,17 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ + +var containsDuplicate = function(nums) { + const duplicate = new Set(); + + for (let i = 0; i < nums.length; i++) { + if (duplicate.has(nums[i])) { + return true; + } + duplicate.add(nums[i]); + } + + return false; +}; From cc399165ac5b60fa71aa78fabdf3e9b9d7c64ab7 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Wed, 4 Dec 2024 17:23:06 +0900 Subject: [PATCH 019/396] feat: [Week 01-2] solve valid-palindrome --- valid-palindrome/Chaedie.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 valid-palindrome/Chaedie.py diff --git a/valid-palindrome/Chaedie.py b/valid-palindrome/Chaedie.py new file mode 100644 index 000000000..9696aa1c5 --- /dev/null +++ b/valid-palindrome/Chaedie.py @@ -0,0 +1,30 @@ +""" +풀이: + 1) lower case로 변형합니다. + 2) alpha numeric 인 문자만 string 배열에 담아줍니다. + 3) string 배열과 string 배열의 역순 배열을 비교해서 return 합니다. + +시간 복잡도: + 1) s.lower() -> O(n) - 각 요소를 순회하며 lower case로 바꿔줍니다. + 2) for char in s: -> O(n) - 각 요소를 순회하면 isalnum() 여부를 확인합니다. + 3) string.append(char) -> O(1) + 4) string[::-1] -> O(n) - 각 요소를 순회합니다. + + 결론: O(4n) 이므로 O(n) 입니다. + +공간 복잡도: + 1) string 배열 - O(n) + + 결론: O(n) 입니다. +""" + + +class Solution: + def isPalindrome(self, s: str) -> bool: + string = [] + s = s.lower() + for char in s: + if char.isalnum(): + string.append(char) + + return string == string[::-1] From eb02143b79f319a6dddab8b9429c4d5a65eed240 Mon Sep 17 00:00:00 2001 From: hanseulhee <3021062@gmail.com> Date: Wed, 4 Dec 2024 17:30:08 +0900 Subject: [PATCH 020/396] add contains duplicate solution explain --- contains-duplicate/hanseulhee.js | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/contains-duplicate/hanseulhee.js b/contains-duplicate/hanseulhee.js index 3147ca063..5df28653a 100644 --- a/contains-duplicate/hanseulhee.js +++ b/contains-duplicate/hanseulhee.js @@ -1,6 +1,12 @@ /** * @param {number[]} nums * @return {boolean} + * + * 접근: 중첩 반복문을 통해 중복이 있으면 true 반환, 중복이 없으면 false를 반환하도록 설계하였습니다. + * 그러나 배열의 요소를 두 번 돌기 때문에 더 효율적인 방법으로 설계하고자 하였습니다. + * + * 해결: 더 효율적인 방법으로 중복 여부를 검사하는 Set을 사용하게 되었습니다. + * Set에 해당 요소가 있는 지 확인하고 있다면 true를 없다면 false를 반환하도록 하였습니다. */ var containsDuplicate = function(nums) { From 829d5a466c4c0460227ae03f79f84e4caaa1f563 Mon Sep 17 00:00:00 2001 From: kdh-92 Date: Wed, 4 Dec 2024 19:03:52 +0900 Subject: [PATCH 021/396] solve : #217 (Contains Duplicate) with Java --- contains-duplicate/kdh-92.java | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 contains-duplicate/kdh-92.java diff --git a/contains-duplicate/kdh-92.java b/contains-duplicate/kdh-92.java new file mode 100644 index 000000000..942931bc8 --- /dev/null +++ b/contains-duplicate/kdh-92.java @@ -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 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; + } +} From 9e567e55bf13dc3cadb17d37b8d3e463f7409c18 Mon Sep 17 00:00:00 2001 From: Gotprgmer Date: Wed, 4 Dec 2024 20:01:49 +0900 Subject: [PATCH 022/396] add solution: Top K Frequent Elements --- top-k-frequent-elements/Gotprgmer.java | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 top-k-frequent-elements/Gotprgmer.java diff --git a/top-k-frequent-elements/Gotprgmer.java b/top-k-frequent-elements/Gotprgmer.java new file mode 100644 index 000000000..ab0746f1b --- /dev/null +++ b/top-k-frequent-elements/Gotprgmer.java @@ -0,0 +1,28 @@ +// 각 수의 개수를 카운트 하고 카운트 한 값을 기준으로 정렬하여 우선순위 큐로 +// k개를 추출하여 result 리스트에 담는다. + +// 시간복잡도 : O(NlogN) +// 공간복잡도 : O(N) + + +public class SolutionGotprgmer { + + public int[] topKFrequent(int[] nums, int k) { + Map map = new HashMap<>(); + for(int num:nums){ + map.put(num,map.getOrDefault(num,0)+1); + } + PriorityQueue> pq = new PriorityQueue<>( + (e1, e2) -> e2.getValue().compareTo(e1.getValue()) + ); + for (Map.Entry entry : map.entrySet()){ + pq.offer(entry); + } + + int[] result = new int[k]; + for(int ansIdx=0;ansIdx < k; ansIdx++){ + result[ansIdx] = pq.poll().getKey(); + } + return result; + } +} From e14cd76e0c08d370ad4ca2974db0d3539e8656ce Mon Sep 17 00:00:00 2001 From: GangBean Date: Wed, 4 Dec 2024 20:22:41 +0900 Subject: [PATCH 023/396] feat: solve contains-duplicate --- contains-duplicate/GangBean.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 contains-duplicate/GangBean.java diff --git a/contains-duplicate/GangBean.java b/contains-duplicate/GangBean.java new file mode 100644 index 000000000..a66343f82 --- /dev/null +++ b/contains-duplicate/GangBean.java @@ -0,0 +1,12 @@ +import java.util.Arrays; +import java.util.stream.Collectors; + +class Solution { + public boolean containsDuplicate(int[] nums) { + /*** + compare length of array and length of set. + O(n) given that n is length of array nums + */ + return nums.length > Arrays.stream(nums).boxed().collect(Collectors.toSet()).size(); + } +} From dfaae6c116d00809404a3def01a51c8bb58743ab Mon Sep 17 00:00:00 2001 From: GangBean Date: Wed, 4 Dec 2024 20:32:10 +0900 Subject: [PATCH 024/396] feat: solve valid-palindrome --- valid-palindrome/GangBean.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 valid-palindrome/GangBean.java diff --git a/valid-palindrome/GangBean.java b/valid-palindrome/GangBean.java new file mode 100644 index 000000000..121372857 --- /dev/null +++ b/valid-palindrome/GangBean.java @@ -0,0 +1,20 @@ +class Solution { + public boolean isPalindrome(String s) { + /** + * Step 1: Convert the input string to lowercase. -> O(n) + * Step 2: Remove all non-alphanumeric characters using regex. -> O(n) + * Step 3: Use two pointers to compare characters from both ends of the string. -> O(n) + * Total time complexity: O(n), where n is the length of the string. + */ + s = s.toLowerCase(); + s = s.replaceAll("[^a-z0-9]", ""); + int left = 0; + int right = s.length() - 1; + if (right <= 0) return true; + while (left < right) { + if (s.charAt(left++) != s.charAt(right--)) return false; + } + return true; + } +} + From 9ea365d9dfa2a67df0b6d23779a1f673e4fcc652 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Wed, 4 Dec 2024 20:59:51 +0900 Subject: [PATCH 025/396] contains-duplicate solution --- contains-duplicate/wonYeong.java | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 contains-duplicate/wonYeong.java diff --git a/contains-duplicate/wonYeong.java b/contains-duplicate/wonYeong.java new file mode 100644 index 000000000..891b28ada --- /dev/null +++ b/contains-duplicate/wonYeong.java @@ -0,0 +1,10 @@ +class Solution { + public boolean containsDuplicate(int[] nums) { + Arrays.sort(nums); + for(int i = 0; i < nums.length - 1; i++) { + if(nums[i] == nums[i+1]) + return true; + } + return false; + } +} \ No newline at end of file From 9d14ded2441b7a4cf2a294e6f0cc77618d052271 Mon Sep 17 00:00:00 2001 From: Gotprgmer Date: Wed, 4 Dec 2024 21:08:38 +0900 Subject: [PATCH 026/396] fix solution: Valid Palindrome --- valid-palindrome/Gotprgmer.java | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/valid-palindrome/Gotprgmer.java b/valid-palindrome/Gotprgmer.java index 64cd1e2a5..6d78af883 100644 --- a/valid-palindrome/Gotprgmer.java +++ b/valid-palindrome/Gotprgmer.java @@ -8,9 +8,8 @@ // 공간복잡도 : O(n) class Solution_Gotprgmer { - static StringBuilder sb; - public boolean isPalindrome(String s) { - sb = new StringBuilder(); + public boolean validPalindrome(String s) { + StringBuilder sb = new StringBuilder(); for(char charToCheck : s.toCharArray()){ if(!Character.isLetterOrDigit(charToCheck)){ continue; @@ -20,12 +19,6 @@ public boolean isPalindrome(String s) { String originalDirection = sb.toString(); String reDirection = sb.reverse().toString(); - if(originalDirection.equals(reDirection)){ - - return true; - } - else{ - return false; - } + return originalDirection.equals(reDirection); } } From 7dbf837fc29187ce548aed69cf35e2d5fff6006b Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Wed, 4 Dec 2024 21:19:11 +0900 Subject: [PATCH 027/396] :art: add newLine --- contains-duplicate/wonYeong.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/wonYeong.java b/contains-duplicate/wonYeong.java index 891b28ada..dfe3f06a3 100644 --- a/contains-duplicate/wonYeong.java +++ b/contains-duplicate/wonYeong.java @@ -7,4 +7,4 @@ public boolean containsDuplicate(int[] nums) { } return false; } -} \ No newline at end of file +} From d2c0fca4a22054b2938e4cbf606e50aadbc5f5ba Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Wed, 4 Dec 2024 21:24:05 +0900 Subject: [PATCH 028/396] :bug: rename Project --- contains-duplicate/{wonYeong.java => dalpang81.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{wonYeong.java => dalpang81.java} (100%) diff --git a/contains-duplicate/wonYeong.java b/contains-duplicate/dalpang81.java similarity index 100% rename from contains-duplicate/wonYeong.java rename to contains-duplicate/dalpang81.java From afd0af83054144010327ced8b04473e716ff5dcf Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Wed, 4 Dec 2024 22:06:09 +0900 Subject: [PATCH 029/396] add solution: Contains Duplicate #217 --- contains-duplicate/donghyeon95.java | 30 +++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 contains-duplicate/donghyeon95.java diff --git a/contains-duplicate/donghyeon95.java b/contains-duplicate/donghyeon95.java new file mode 100644 index 000000000..f4076156d --- /dev/null +++ b/contains-duplicate/donghyeon95.java @@ -0,0 +1,30 @@ +import java.util.*; + +class Solution { + public boolean containsDuplicate(int[] nums) { + /* + * -- 풀이 -- + * nums를 순회하면서 HashSet에 데이터를 넣어서 중복되었는 지 확인한다. + * + * -- 시간 복잡도 -- + * 길이 N인 nums를 순환하는데 대한 시간 복잡도 => O(N) + * hashSet의 add에 대한 시간 복잡도 => O(1) + * 전체 시간 복잡도 O(1)*O(N) =O(n) + * ------------------------------------------ + * + * -- 공간 복잡도 -- + * 길이 N인 nums를 넣을 Hashset이 있어야 하기에 O(N) + * ------------------------------------------- + */ + + // 중복을 확인할 수 있는 set 선언 + HashSet hashSet = new HashSet<>(); + + for (int num: nums) { + // set에 있다면 + if (!hashSet.add(num)) return true; + } + + return false; + } +} \ No newline at end of file From 00fb70bdb71a2a8aa93e781580729145d177c546 Mon Sep 17 00:00:00 2001 From: changchanghwang Date: Wed, 4 Dec 2024 22:16:28 +0900 Subject: [PATCH 030/396] house robber --- house-robber/changchanghwang.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 house-robber/changchanghwang.go diff --git a/house-robber/changchanghwang.go b/house-robber/changchanghwang.go new file mode 100644 index 000000000..2b4e1c191 --- /dev/null +++ b/house-robber/changchanghwang.go @@ -0,0 +1,14 @@ +// time complexity: O(n) +// space complexity: O(1) +func rob(nums []int) int { + prev := 0 + curr := 0 + + for _, num := range nums { + temp := curr + curr = max(prev+num, curr) + prev = temp + } + + return curr +} From fe10e8f539502b6cc617f34830e4299462efde76 Mon Sep 17 00:00:00 2001 From: mintheon Date: Thu, 5 Dec 2024 01:54:26 +0900 Subject: [PATCH 031/396] valid-palindrome solution --- valid-palindrome/mintheon.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 valid-palindrome/mintheon.java diff --git a/valid-palindrome/mintheon.java b/valid-palindrome/mintheon.java new file mode 100644 index 000000000..04a23f135 --- /dev/null +++ b/valid-palindrome/mintheon.java @@ -0,0 +1,27 @@ +class Solution { + public boolean isPalindrome(String s) { + int start = 0; + int end = s.length() - 1; + + while(start < end) { + if(!Character.isLetterOrDigit(s.charAt(start))) { + start++; + continue; + } + + if(!Character.isLetterOrDigit(s.charAt(end))){ + end--; + continue; + } + + if(Character.toLowerCase(s.charAt(start)) != Character.toLowerCase(s.charAt(end))) { + return false; + } + + start++; + end--; + } + + return true; + } +} \ No newline at end of file From 308bb830909a8337f875bfffa56673b952b357c5 Mon Sep 17 00:00:00 2001 From: mintheon Date: Thu, 5 Dec 2024 01:57:30 +0900 Subject: [PATCH 032/396] contains-duplicate solution --- contains-duplicate/mintheon.java | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 contains-duplicate/mintheon.java diff --git a/contains-duplicate/mintheon.java b/contains-duplicate/mintheon.java new file mode 100644 index 000000000..659af83cc --- /dev/null +++ b/contains-duplicate/mintheon.java @@ -0,0 +1,13 @@ +import java.util.Arrays; + +class Solution { + public boolean containsDuplicate(int[] nums) { + Arrays.sort(nums); + for(int i = 1; i < nums.length; i++) { + if(nums[i] == nums[i - 1]) { + return true; + } + } + return false; + } +} \ No newline at end of file From e09178a625b0cc0962cf3d45d3ab92e586c5ad8c Mon Sep 17 00:00:00 2001 From: kdh-92 Date: Thu, 5 Dec 2024 02:00:25 +0900 Subject: [PATCH 033/396] solve : #220 (valid-palindrome) with Java --- valid-palindrome/kdh-92.java | 65 ++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 valid-palindrome/kdh-92.java diff --git a/valid-palindrome/kdh-92.java b/valid-palindrome/kdh-92.java new file mode 100644 index 000000000..21fa3f61b --- /dev/null +++ b/valid-palindrome/kdh-92.java @@ -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) + // 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); + + return IntStream.range(0, filtered.length() / 2) + .allMatch(i -> filtered.charAt(i) == filtered.charAt(filtered.length() - 1 - i)); + } +} From ff5969e1d6976d0c3d54fcbabfa300e6d6ae552f Mon Sep 17 00:00:00 2001 From: mintheon Date: Thu, 5 Dec 2024 02:06:53 +0900 Subject: [PATCH 034/396] top-k-frequent-elements solution --- top-k-frequent-elements/mintheon.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 top-k-frequent-elements/mintheon.java diff --git a/top-k-frequent-elements/mintheon.java b/top-k-frequent-elements/mintheon.java new file mode 100644 index 000000000..7a2dd0cfb --- /dev/null +++ b/top-k-frequent-elements/mintheon.java @@ -0,0 +1,24 @@ +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.PriorityQueue; + +class Solution { + public int[] topKFrequent(int[] nums, int k) { + int[] answer = new int[k]; + Map frequent = new HashMap<>(); + + for(int num: nums) { + frequent.put(num, frequent.getOrDefault(num, 1) + 1); + } + + PriorityQueue> pq = new PriorityQueue<>((a, b) -> b.getValue().compareTo(a.getValue())); + pq.addAll(frequent.entrySet()); + + for(int i = 0; i < k; i++) { + answer[i] = pq.poll().getKey(); + } + + return answer; + } +} \ No newline at end of file From 270473dc2411f1c2219a61ca727a66ca4b5f578b Mon Sep 17 00:00:00 2001 From: pmjuu Date: Wed, 4 Dec 2024 14:18:54 -0500 Subject: [PATCH 035/396] feat: solve contains duplicate --- contains-duplicate/pmjuu.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 contains-duplicate/pmjuu.py diff --git a/contains-duplicate/pmjuu.py b/contains-duplicate/pmjuu.py new file mode 100644 index 000000000..0648d87c5 --- /dev/null +++ b/contains-duplicate/pmjuu.py @@ -0,0 +1,3 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) != len(set(nums)) From 06d5ee3169b7de6b2d2c74142969e1e6c0b119e5 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Thu, 5 Dec 2024 07:50:18 +0900 Subject: [PATCH 036/396] feat: [Week 01-3] solve Top K Frequent Elements --- top-k-frequent-elements/Chaedie.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 top-k-frequent-elements/Chaedie.py diff --git a/top-k-frequent-elements/Chaedie.py b/top-k-frequent-elements/Chaedie.py new file mode 100644 index 000000000..5b6241049 --- /dev/null +++ b/top-k-frequent-elements/Chaedie.py @@ -0,0 +1,29 @@ +""" +Solution: + 1. make a dictionary of (index, Frequency) + 2. sort the items of dictionary by Frequency + 3. return list of Top k Frequent Elements + +Time Complexity: + 1. iterate nums for counting -> O(n) + 2. sort -> O(n log n) + 3. iterate list for making return value -> O(n) + + So Time complexity of this solution is O(n log n) + +Space Complexity: + 1. dictionary for counting frequency of nums -> O(n) + 2. sorted List -> O(n) + + Space complexity of this solution is O(n) +""" + + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + counts = defaultdict(int) + for num in nums: + counts[num] += 1 + + result = sorted(counts.items(), key=lambda x: x[1], reverse=True) + return list(map(lambda x: x[0], result[:k])) From 3cd41b5a8b38131311b73629ce3b1385924137b7 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Thu, 5 Dec 2024 08:09:48 +0900 Subject: [PATCH 037/396] feat: [Week 01-4] solve longest-consecutive-sequence --- longest-consecutive-sequence/Chaedie.py | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 longest-consecutive-sequence/Chaedie.py diff --git a/longest-consecutive-sequence/Chaedie.py b/longest-consecutive-sequence/Chaedie.py new file mode 100644 index 000000000..a41d5183b --- /dev/null +++ b/longest-consecutive-sequence/Chaedie.py @@ -0,0 +1,46 @@ +""" +Solution: + 0. i will use prev, cur pointers in for loop, + so i have to get rid of edge case when len of nums is at most 1 + 1. use hash set for remove duplicate elements + 2. sort list + 3. iterate sorted_nums and use two pointers (prev, cur) + compare prev and cur and count if the difference is 1 + 4. use max method, memorize maxCount + 5. return maxCount + +Time Complexity: + 1. remove duplicate by hash set -> O(n) + 2. sort the list -> O(n log n) + 3. iterate sorted_nums -> O(n) + + so time complexity of this solution will be O(n log n) + +Space Complexity: + 1. set() -> O(n) + 2. sorted_nums -> O(n) + 3. count , maxCount -> O(1) + + space complexity of this solution will be O(n) +""" + + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + if len(nums) <= 1: + return len(nums) + + sorted_nums = sorted(list(set(nums))) + + count = 1 + maxCount = 1 + for i in range(1, len(sorted_nums)): + prev = sorted_nums[i - 1] + cur = sorted_nums[i] + if prev + 1 == cur: + count += 1 + maxCount = max(count, maxCount) + else: + count = 1 + + return maxCount From 842f1fc2a83f4737c93f954111e96a842ad32f83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Thu, 5 Dec 2024 15:23:19 +0900 Subject: [PATCH 038/396] contains-duplicate --- contains-duplicate/EcoFriendlyAppleSu.kt | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 contains-duplicate/EcoFriendlyAppleSu.kt diff --git a/contains-duplicate/EcoFriendlyAppleSu.kt b/contains-duplicate/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..8b5ad1db6 --- /dev/null +++ b/contains-duplicate/EcoFriendlyAppleSu.kt @@ -0,0 +1,13 @@ +package leetcode_study + +/** + * Set 자료 구조로 변경 후 원소의 개수를 비교해 문제 해결 + * 시간 복잡도 : O(n) + * -> 모든 Array의 원소를 순회해야함. + * 공간 복잡도 : O(n) + * -> IntArray의 요소 개수에 비례하여 추가적인 공간이 필요함. + */ +fun containsDuplicate(nums: IntArray): Boolean { + val changeSet = nums.toSet() + return changeSet.size != nums.size +} From 6dbea54f1419aedc532cee1afe88848afcce7bc7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Thu, 5 Dec 2024 16:22:00 +0900 Subject: [PATCH 039/396] Valid Palindrome --- valid-palindrome/EcoFriendlyAppleSu.kt | 33 ++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 valid-palindrome/EcoFriendlyAppleSu.kt diff --git a/valid-palindrome/EcoFriendlyAppleSu.kt b/valid-palindrome/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..f7beadc2e --- /dev/null +++ b/valid-palindrome/EcoFriendlyAppleSu.kt @@ -0,0 +1,33 @@ +package leetcode_study + +/** + * 문자열의 대칭 판단 + * 시간 복잡도 : O(n) + * -> 주어진(n) 크기의 문자열을 순회하며 비교함 + */ +fun isPalindrome(s: String): Boolean { + + // 주어진 문자열에서 모든 non-alphanumeric characters를 필터한 문자 배열 할당 + val splitGivenString = s.toCharArray() + .filter { it.isLetter() || it.isDigit() } + .map { it.lowercaseChar() } + .toCharArray() + + // 필터된 문자열이 비어있다면 true 반환 + if (splitGivenString.isEmpty()) { return true } + + // 대칭을 비교하기 위한 시작, 끝 변수 + var start = 0 + var end = splitGivenString.size - 1 + + // 반복적으로 수행하며 같다면 시작 +1, 끝 -1 을 진행해 대칭 판단 + while (start <= end) { + if (splitGivenString[start] == splitGivenString[end]) { + start += 1 + end -= 1 + continue + } + return false + } + return true +} From 192d7d5a75fef619f9e0f2cac64ca3c986c8b4e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Thu, 5 Dec 2024 17:15:03 +0900 Subject: [PATCH 040/396] Top K Frequent Elements --- top-k-frequent-elements/EcoFriendlyAppleSu.kt | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 top-k-frequent-elements/EcoFriendlyAppleSu.kt diff --git a/top-k-frequent-elements/EcoFriendlyAppleSu.kt b/top-k-frequent-elements/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..e171f6131 --- /dev/null +++ b/top-k-frequent-elements/EcoFriendlyAppleSu.kt @@ -0,0 +1,23 @@ +package leetcode_study + +/** + * 주어진 숫자들에서 빈도 수가 가장 큰 k 개의 숫자를 구하는 문제. map 자료구조를 사용해 해결 + * 시간 복잡도 : O(n) + * -> Int Array를 순회해 map에 담는 과정 + * 공간 복잡도 : O(n) + * -> Int Array에 존재하는 유니크한 요소 만큼 필요함. + */ +fun topKFrequent(nums: IntArray, k: Int): IntArray { + val map = mutableMapOf() + + for (i in nums.indices) { + if (map.containsKey(nums[i])) { + val value = map[nums[i]]!! + map[nums[i]] = value + 1 + } else { + map.putIfAbsent(nums[i], 1) + } + } + val sortedMap = map.toList().sortedByDescending { it.second }.toMap() + return sortedMap.entries.take(k).map { it.key }.toIntArray() +} From 8937108a35b00533a10aae0481ab7da4a48701f4 Mon Sep 17 00:00:00 2001 From: hanseulhee <3021062@gmail.com> Date: Thu, 5 Dec 2024 18:12:53 +0900 Subject: [PATCH 041/396] valid palindrome solution --- valid-palindrome/hanseulhee.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 valid-palindrome/hanseulhee.js diff --git a/valid-palindrome/hanseulhee.js b/valid-palindrome/hanseulhee.js new file mode 100644 index 000000000..3b5f2514d --- /dev/null +++ b/valid-palindrome/hanseulhee.js @@ -0,0 +1,24 @@ +/** + * @param {string} s + * @return {boolean} + * + * 해결: 먼저 문자열의 정방향, 역방향 비교를 위해 문자열을 소문자로 변환하였으며 특수기호는 제외하였습니다. + * 정방향과 역방향을 비교하여 문자가 모두 일치하면 true 아니라면 false를 반환하였습니다. + */ +var isPalindrome = function (s) { + const filterS = s.toLowerCase().replace(/[^a-z0-9]/g, ""); + + let left = 0; + let right = filterS.length - 1; + + while (left < right) { + if (filterS[left] !== filterS[right]) { + return false; + } else { + left++; + right--; + } + } + + return true; +}; From 4579911fa03ea759fc9a7f71fee2c45b77cb9ed4 Mon Sep 17 00:00:00 2001 From: yoonsang lee Date: Thu, 5 Dec 2024 19:42:13 +0900 Subject: [PATCH 042/396] add: solution01 --- contains-duplicate/ysle0.go | 55 +++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 contains-duplicate/ysle0.go diff --git a/contains-duplicate/ysle0.go b/contains-duplicate/ysle0.go new file mode 100644 index 000000000..2fd2018ed --- /dev/null +++ b/contains-duplicate/ysle0.go @@ -0,0 +1,55 @@ +package contains_duplicate + +import "sort" + +/* +1. 문제 + + 주어진 int 배열 nums에 숫자가 중복되는 경우가 한 번이라도 있으면 true, 그렇지 않으면 false 를 리턴 + +2. 풀이 + + 고유값만 저장하는 set(go 에서는 map)의 성질을 활용하여 + nums를 순회하며 set에 값이 있는지 없는지 체크하여 + 숫자가 중복되는 경우를 체크 + +3. 분석 + - 시간 복잡도: O(N) + nums 탐색: O(N) + 배열 nums의 모든 원소를 단 한 번 순회 + map 삽입, 탐색: O(1) + map의 내부 구현은 해시 테이블. + O(N)보다 작아 무시됨 + - 공간 복잡도: O(N) + 최악의 경우라도 사용공간은 nums 의 크기만큼 + nums의 모든 원소를 포함한 map +*/ +func containsDuplicate(nums []int) bool { + seen := map[int]int{} + + for _, n := range nums { + if _, ok := seen[n]; ok { + return true + } + + seen[n] = 1 + } + + return false +} + +func containsDuplicate_SortedApproach(nums []int) bool { + // early exit for small slices + if len(nums) < 2 { + return false + } + + // sort in ascending order and check adjacent elements + sort.Ints(nums) + for i := 1; i < len(nums); i++ { + if nums[i] == nums[i-1] { + return true + } + } + + return false +} From b38e74beb9af3331cf53dc14f436e22529daa8e7 Mon Sep 17 00:00:00 2001 From: yoonsang lee Date: Thu, 5 Dec 2024 19:42:26 +0900 Subject: [PATCH 043/396] add: solution02 --- valid-palindrome/ysle0.go | 92 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 valid-palindrome/ysle0.go diff --git a/valid-palindrome/ysle0.go b/valid-palindrome/ysle0.go new file mode 100644 index 000000000..21770bbd0 --- /dev/null +++ b/valid-palindrome/ysle0.go @@ -0,0 +1,92 @@ +package valid_palindrome + +import ( + "regexp" + "strings" +) + +/* + 1. 문제 + 회문. 주어진 문자열 s 를 모두 소문자로 바꾸고, alphanumeric 이 아닌 문자를 제외할 때, + 앞으로 읽으나 뒤로 읽으나 같은 문자열인지 체크 (회문) + + 2. 풀이 + - 주어진 문자열 s 에서 alphanumeric character 만 남기고 제거. + - 모두 소문자로 변환 + - 앞, 뒤로 인덱스 위치를 기록하는 cursor 를 정의 + 커서 둘을 앞, 뒤로 전진하며 같지않은 문자가 나오면 false 를 반환, 그렇지 않고 회문이면 true 를 반환. + +3. 분석 + - 시간 복잡도: O(N) + regex.ReplaceAllString(): O(n) + 모든 문자열을 돌며 regex 검사 후 대체 + strings.ToLower(str): O(n) + 모든 문자열을 돌며 소문자로 변환 + palindrome 문자열 체크 loop + 앞 커서 < 뒤 커서 의 조건으로 O(n/2) ---> O(n) + - 공간 복잡도: O(1) + 새로운 저장공간은 없으며 주어진 문자열 s 하나뿐 +*/ +var nonAlphanumericRegex = regexp.MustCompile(`[^a-zA-Z0-9]+`) + +func isPalindrome(s string) bool { + s = nonAlphanumericRegex.ReplaceAllString(s, "") + s = strings.ToLower(s) + // 앞, 뒤 커서 + front, rear := 0, len(s)-1 + + for front < rear { + frontCh := s[front] + readCh := s[rear] + + // 선택한 두 문자가 다르면 실패! + if frontCh != readCh { + return false + } + + front++ + rear-- + } + + return true +} + +/* +1. 개선점 + - regex 오버헤드 제거 +*/ +func isPalindrome_Optimized(s string) bool { + front, rear := 0, len(s)-1 + + for front < rear { + for front < rear && !isAlphanumeric(s[front]) { + front++ + } + + for front < rear && !isAlphanumeric(s[rear]) { + rear-- + } + + if toLower(s[front]) != toLower(s[rear]) { + return false + } + + front++ + rear-- + } + + return true +} + +func isAlphanumeric(ch byte) bool { + return (ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') +} + +func toLower(ch byte) byte { + if ch >= 'A' && ch <= 'Z' { + return ch + 32 + } + return ch +} From 2f3492ba39ca57d2e21daa36ef4e8053d3a0d483 Mon Sep 17 00:00:00 2001 From: yoonsang lee Date: Thu, 5 Dec 2024 19:42:36 +0900 Subject: [PATCH 044/396] add: solution03 --- top-k-frequent-elements/ysle0.go | 127 +++++++++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 top-k-frequent-elements/ysle0.go diff --git a/top-k-frequent-elements/ysle0.go b/top-k-frequent-elements/ysle0.go new file mode 100644 index 000000000..34e34948c --- /dev/null +++ b/top-k-frequent-elements/ysle0.go @@ -0,0 +1,127 @@ +package top_k_frequent_elements + +//package main + +import ( + "container/heap" + "slices" +) + +/* + 1. 문제 + nums 에서 가장 많이 나온 숫자들 k 개를 반환. + + 2. 풀이 + map 에 빈도를 기록하여 내림차순 정렬한 후 k개 뽑기 + +3. 분석 + + - 시간 복잡도: O(N + M logM) --> O(N logN) + 빈도맵핑을 위한 nums 순회: O(N) + 오름차순정렬: O(M logM) + + - 공간 복잡도: O(N) + 주어진 배열 nums: O(N) + 빈도맵핑용 map: O(N) +*/ +type Kvp struct { + k int + v int +} + +func topKFrequent(nums []int, k int) []int { + freq := map[int]int{} + + // 빈도를 기록 + for _, n := range nums { + if _, ok := freq[n]; !ok { + freq[n] = 1 + } else { + freq[n]++ + } + } + + // map->array + tmp := make([]Kvp, 0, len(freq)) + for key, v := range freq { + tmp = append(tmp, Kvp{key, v}) + } + + // 내림차순 정렬 (time O(M logM) + slices.SortFunc(tmp, func(a, b Kvp) int { return b.v - a.v }) + + // []int 로 변환 + res := make([]int, 0, len(tmp)) + for _, kvp := range tmp { + res = append(res, kvp.k) + } + + // k 개 뽑기 + return res[:k] +} + +func topKElements_HeapBasedApproach(nums []int, k int) []int { + freq := map[int]int{} + for _, n := range nums { + freq[n]++ + } + + h := &IntHeap{} + heap.Init(h) + + for k, v := range freq { + heap.Push(h, Kvp{k, v}) + if h.Len() > k { + heap.Pop(h) + } + } + + res := make([]int, k) + for i := k - 1; i >= 0; i-- { + res[i] = heap.Pop(h).(Kvp).k + } + + return res +} + +type IntHeap []Kvp + +func (h *IntHeap) Len() int { return len(*h) } +func (h *IntHeap) Less(i, j int) bool { return (*h)[i].v < (*h)[j].v } +func (h *IntHeap) Swap(i, j int) { (*h)[i], (*h)[j] = (*h)[j], (*h)[i] } +func (h *IntHeap) Push(x interface{}) { *h = append(*h, x.(Kvp)) } +func (h *IntHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[0 : n-1] + return x +} + +func topKFrequentElements_BucketSort(nums []int, k int) []int { + freq := map[int]int{} + for _, n := range nums { + freq[n]++ + } + + buc := make([][]int, len(nums)+1) + for k, v := range freq { + buc[v] = append(buc[v], k) + } + + res := []int{} + for i := len(buc) - 1; i >= 0 && len(res) < k; i-- { + res = append(res, buc[i]...) + } + + return res[:k] +} + +// +//func main() { +// r1 := topKFrequent([]int{1, 1, 1, 2, 2, 3}, 2) +// fmt.Println(r1) +// +// r2 := topKFrequent([]int{1}, 1) +// fmt.Println(r2) +//} From 845c93fb7ec7671602569360944b5a80187b137e Mon Sep 17 00:00:00 2001 From: yoonsang lee Date: Thu, 5 Dec 2024 19:42:43 +0900 Subject: [PATCH 045/396] add: solution04 --- longest-consecutive-sequence/ysle0.go | 72 +++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 longest-consecutive-sequence/ysle0.go diff --git a/longest-consecutive-sequence/ysle0.go b/longest-consecutive-sequence/ysle0.go new file mode 100644 index 000000000..b4fcb500a --- /dev/null +++ b/longest-consecutive-sequence/ysle0.go @@ -0,0 +1,72 @@ +package longest_consecutive_sequence + +import "slices" + +/* + 1. 문제 + 주어진 int 배열 nums에서 찾을 수 있는 가장 긴 연속된 원소의 길이 구하기 + + 2. 풀이 + 모든 수의 중복을 제거하고, 오름차순으로 정렬하여 연속된 원소의 부분을 찾기 위해서 + 배열을 순회하여 인덱스 고정~전진하며 다음 원소가 연속된 원소인지 체크를 반복 + +3. 분석 + + - 시간 복잡도: O(N logN) + 배열 정렬 O(N logN) + 중복된 원소를 제거해주는 slices.Compact(nums): O(N) + 2중 포문은 for 문 순회 index 를 같이 쓰므로 O(N) + + - 공간 복잡도: O(N) +*/ +func longestConsecutive(nums []int) int { + if len(nums) == 0 { + return 0 + } + + if len(nums) == 1 { + return 1 + } + + slices.Sort(nums) + nums = slices.Compact(nums) + // 중복을 제거하고 나서도 1개면 최장연속수는 1 + if len(nums) == 1 { + return 1 + } + + cons := map[int]int{} + cursor := 0 + for cursor < len(nums)-1 { + cons[cursor] = 1 + wasConsecutive := false + + // cursor 는 고정하고, innerCursor 를 돌림 + innerCursor := cursor + for innerCursor+1 < len(nums) && + nums[innerCursor]+1 == nums[innerCursor+1] { + + cons[cursor]++ + innerCursor++ + wasConsecutive = true + } + + if wasConsecutive { + cursor = innerCursor + } + cursor++ + } + + //tmp := make([]int, 0, len(cons)) + tmp := make([]int, 0, len(cons)) + for _, v := range cons { + tmp = append(tmp, v) + } + + slices.SortFunc( + tmp, + func(a, b int) int { + return b - a + }) + return tmp[0] +} From d1f77501ca07e214aadb954ef25718a743d8234a Mon Sep 17 00:00:00 2001 From: ekgns33 Date: Thu, 5 Dec 2024 19:42:57 +0900 Subject: [PATCH 046/396] feat : contains duplicate --- contains-duplicate/ekgns33.java | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 contains-duplicate/ekgns33.java diff --git a/contains-duplicate/ekgns33.java b/contains-duplicate/ekgns33.java new file mode 100644 index 000000000..2c74dbea7 --- /dev/null +++ b/contains-duplicate/ekgns33.java @@ -0,0 +1,49 @@ +import java.util.HashSet; +import java.util.Set; + +/* +start 7:06~7:14 PASS +input : integer array +output : return if input contains duplicate +constraint : +1) empty array? + nope. at least one +2) size? + [1, 10^5] +3) sorted? + nope. +4) range of elements in the array? + [-10^9, 10^9] >> max 2 * 10*9 +1 + +brute force: +ds : array. algo : just nested for-loop +iterate through the array, for index i 0 to n. n indicates the size of input + nested loop fo r index j from i+1 to n + if nums[j] == nums[i] return true; + +return false; + +time : O(n^2), space : O(1) + +better: +ds : hashset. algo : one for-loop +iterate through the array: + if set contains current value: + return true; + else + add current value to set + +return false; +time : O(n) space :O(n) + + */ +class Solution { + public boolean containsDuplicate(int[] nums) { + Set set = new HashSet<>(); + for(int num : nums) { + if(set.contains(num)) return true; + set.add(num); + } + return false; + } +} From 9694699c9cecc7c47935b76d80325d1a0fc7dd23 Mon Sep 17 00:00:00 2001 From: ekgns33 Date: Thu, 5 Dec 2024 19:43:14 +0900 Subject: [PATCH 047/396] feat : valid palindrome --- valid-palindrome/ekgns33.java | 75 +++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 valid-palindrome/ekgns33.java diff --git a/valid-palindrome/ekgns33.java b/valid-palindrome/ekgns33.java new file mode 100644 index 000000000..b65b10001 --- /dev/null +++ b/valid-palindrome/ekgns33.java @@ -0,0 +1,75 @@ +/* +start : 7:18 ~ +input : String s +output : return if given s is valid palindrome +constraint: +1) valid palindrome? + convert all uppercase letter to lowercase, + remove non-alphanumeric chars, + reads same forward and backward. + ex) abba, aba, a, aacbcaa +2) length of the input string + [1, 2*10^5] +3) does input string contains non-alphanumeric chars? such as whitespace + yes, but only ASCII chars + +------- + +brute force: +read each character of input string. +create a new string that only contains +lowercase letters and numbers << O(n), when n is length of string s + +create string which one is reversed. < O(n) + +compare. < O(n) + +time : O(n)-3loops, space : O(n) + +------- +better : two-pointer + +same as brute force. build new string. + +use two pointer left and right + +while left <= right + if s[left] != s[right] return false; + +return true; +------- +optimal : + +use two pointer left and right +while left <= right + if s[left] is non-alpha left++ + elif s[right] is non-alpha right-- + elif s[left] != s[right] return false + else left++ right-- + +return true +time : O(n) space : O(1) + */ +class Solution { + public boolean isPalindrome(String s) { + int left = 0; + int right = s.length() - 1; + char leftC; + char rightC; + while(left <= right) { + leftC = s.charAt(left); + rightC = s.charAt(right); + if(!Character.isLetterOrDigit(leftC)) { + left++; + } else if (!Character.isLetterOrDigit(rightC)) { + right--; + } else if (Character.toLowerCase(leftC) != Character.toLowerCase(rightC)) { + return false; + } else { + left++; + right--; + } + } + return true; + } +} From df80b675833613946c1cb223f9c2ea4e8f4b7c2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Thu, 5 Dec 2024 23:51:02 +0900 Subject: [PATCH 048/396] Longest Consecutive Sequence --- .../EcoFriendlyAppleSu.kt | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 longest-consecutive-sequence/EcoFriendlyAppleSu.kt diff --git a/longest-consecutive-sequence/EcoFriendlyAppleSu.kt b/longest-consecutive-sequence/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..993354e25 --- /dev/null +++ b/longest-consecutive-sequence/EcoFriendlyAppleSu.kt @@ -0,0 +1,57 @@ +package leetcode_study + +/** + * HashSet을 사용한 풀이. + * 시간 복잡도 O(n) + * -> Loop를 두 번 돌기 때문에 O(n^2)이라고 생각할 수 있으나 최악의 상황이여도 O(n + (n-1))로 O(n)이 됨. + * -> 1 부터 10억까지의 연속된 수가 Set 자료구조에 담겨 있고 최악의 상황으로 1이 마지막 순번에 뽑힌다고 가정했을 때, (Set은 순서가 존재하지 않음) + * -> 1 부터 Longest Count 하더라도 주어진 nums에서 n 번 set에서 10억 -1번을 순회하므로 O(n^2)이 아닌 O(n)이 됨. + */ +fun longestConsecutive(nums: IntArray): Int { + val numSet: HashSet = nums.toHashSet() + var longest = 0 + + for (num in nums) { + // 현재 요소보다 크기가 1 작은 숫자를 갖고 있다면 현재 요소는 최소값이 아니므로 다음으로 넘어감 + if (numSet.contains(num -1)) { + continue + } + // 현재 요소보다 1 작은 연속된 숫자가 없으므로 현재 원소를 1 카운트 한 length 할당 + var length = 1 + while (numSet.contains(num + length)) { + length++ + } + longest = max(longest, length) + } + return longest +} + +/** + * Time Limit 발생. + * 시간 복잡도 O(n^2) + * -> nums 안에 존재하는 요소마다 중복을 포함한 Loop(while) 진행 + */ +fun longestConsecutive01(nums: IntArray): Int { + // 결과를 담을 리스트 + val resultList = mutableListOf() + + // 1차 loop + for (i in nums.indices) { + var tempResult = 0 + var currentNum = nums[i] + // 2차 loop + while (true) { + if (nums.contains(currentNum)) { + tempResult += 1 + currentNum += 1 + } else { + break + } + } + resultList.add(tempResult) + } + if (resultList.isEmpty()) { + return 0 + } + return resultList.max() +} From f56e213406973b09fbdaa93c7be773dbf04c7f89 Mon Sep 17 00:00:00 2001 From: jeehay Date: Thu, 5 Dec 2024 23:51:43 +0900 Subject: [PATCH 049/396] contains-duplicate solution --- contains-duplicate/Jeehay28.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 contains-duplicate/Jeehay28.js diff --git a/contains-duplicate/Jeehay28.js b/contains-duplicate/Jeehay28.js new file mode 100644 index 000000000..fcfb8589d --- /dev/null +++ b/contains-duplicate/Jeehay28.js @@ -0,0 +1,7 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function (nums) { + return nums.length !== new Set(nums).size; +}; From a674237946b916cedd266e2b0ccfb76dc732776e Mon Sep 17 00:00:00 2001 From: selim-jo Date: Thu, 5 Dec 2024 15:13:34 +0900 Subject: [PATCH 050/396] contains duplicate solution --- contains-duplicate/limlimjo.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 contains-duplicate/limlimjo.js diff --git a/contains-duplicate/limlimjo.js b/contains-duplicate/limlimjo.js new file mode 100644 index 000000000..e694b957b --- /dev/null +++ b/contains-duplicate/limlimjo.js @@ -0,0 +1,23 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + + // 첫 번째 방법: filter + indexOf 사용 => indexOf(),filter() 각각 시간복잡도 O(n) 두 개가 중첩이므로 시간복잡도 O(n^2) + // Runtime: Time Limit Exceeded 발생 + const method1 = function() { + const filterNums = nums.filter((item,index) => nums.indexOf(item) !== index); + return filterNums.length > 0; + } + + // 두 번째 방법: Set 사용 => nums 배열을 set으로 변환할 때 한번씩 확인하면 되므로 시간복잡도 O(n) + // Runtime: 14ms + const method2 = function() { + const setNums = new Set(nums); + return setNums.size !== nums.length; + } + + // 위 두 가지 방법 중 Set을 사용하는 것이 성능상 훨씬 나음 + return method2(); +}; From 4a49e74ec68f074e34dcb81e2b955bbc08a1cca9 Mon Sep 17 00:00:00 2001 From: jeehay Date: Thu, 5 Dec 2024 23:54:24 +0900 Subject: [PATCH 051/396] valid-palindrome solution --- valid-palindrome/Jeehay28.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 valid-palindrome/Jeehay28.js diff --git a/valid-palindrome/Jeehay28.js b/valid-palindrome/Jeehay28.js new file mode 100644 index 000000000..3652e8a5f --- /dev/null +++ b/valid-palindrome/Jeehay28.js @@ -0,0 +1,17 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function (s) { + const reg = /[a-z0-9]/g; + const converted = s.toLowerCase().match(reg); + + if (converted === null) { + return true; + } else { + const forward = converted.join(""); + const backward = converted.reverse().join(""); + + return forward === backward; + } +}; From cb4e36b7f85afb4ee04091299bbb21c91fdcb16d Mon Sep 17 00:00:00 2001 From: mintheon Date: Fri, 6 Dec 2024 01:03:34 +0900 Subject: [PATCH 052/396] =?UTF-8?q?fix:=20=EC=BD=94=EB=93=9C=20=EB=A7=88?= =?UTF-8?q?=EC=A7=80=EB=A7=89=20=EA=B0=9C=ED=96=89=EC=B2=98=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/mintheon.java | 2 +- top-k-frequent-elements/mintheon.java | 2 +- valid-palindrome/mintheon.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contains-duplicate/mintheon.java b/contains-duplicate/mintheon.java index 659af83cc..1af3d32f8 100644 --- a/contains-duplicate/mintheon.java +++ b/contains-duplicate/mintheon.java @@ -10,4 +10,4 @@ public boolean containsDuplicate(int[] nums) { } return false; } -} \ No newline at end of file +} diff --git a/top-k-frequent-elements/mintheon.java b/top-k-frequent-elements/mintheon.java index 7a2dd0cfb..da00d043f 100644 --- a/top-k-frequent-elements/mintheon.java +++ b/top-k-frequent-elements/mintheon.java @@ -21,4 +21,4 @@ public int[] topKFrequent(int[] nums, int k) { return answer; } -} \ No newline at end of file +} diff --git a/valid-palindrome/mintheon.java b/valid-palindrome/mintheon.java index 04a23f135..f284704e3 100644 --- a/valid-palindrome/mintheon.java +++ b/valid-palindrome/mintheon.java @@ -24,4 +24,4 @@ public boolean isPalindrome(String s) { return true; } -} \ No newline at end of file +} From 15c9c082ff0a723b997534b4e446d7dd2de02130 Mon Sep 17 00:00:00 2001 From: jeehay Date: Fri, 6 Dec 2024 01:07:11 +0900 Subject: [PATCH 053/396] top-k-frequent-elements solution --- top-k-frequent-elements/Jeehay28.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 top-k-frequent-elements/Jeehay28.js diff --git a/top-k-frequent-elements/Jeehay28.js b/top-k-frequent-elements/Jeehay28.js new file mode 100644 index 000000000..b127890ef --- /dev/null +++ b/top-k-frequent-elements/Jeehay28.js @@ -0,0 +1,25 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function (nums, k) { + let result = []; + + const obj = nums.reduce((acc, cur) => { + acc[cur] = (acc[cur] || 0) + 1; + return acc; + }, {}); + + const frequentValues = Object.values(obj) + .sort((a, b) => b - a) + .slice(0, k); + + for (const [key, value] of Object.entries(obj)) { + if (frequentValues.includes(value)) { + result.push(parseInt(key)); + } + } + + return result; +}; From 1c65b023edd0bf34c1615470050f46b24bbc5110 Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Fri, 6 Dec 2024 11:02:35 +0900 Subject: [PATCH 054/396] contains duplicate sol --- contains-duplicate/oyeong011.cpp | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 contains-duplicate/oyeong011.cpp diff --git a/contains-duplicate/oyeong011.cpp b/contains-duplicate/oyeong011.cpp new file mode 100644 index 000000000..df718d29c --- /dev/null +++ b/contains-duplicate/oyeong011.cpp @@ -0,0 +1,14 @@ +#include +using namespace std; +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_map mp; + for(int a : nums){ + if(++mp[a] >= 2){ + return true; + } + } + return false; + } +}; \ No newline at end of file From 9bc5e4ea20734c62c69ad73b9c7974ca9fd5c798 Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Fri, 6 Dec 2024 11:03:09 +0900 Subject: [PATCH 055/396] valid palindrome sol --- valid-palindrome/oyeong011.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 valid-palindrome/oyeong011.cpp diff --git a/valid-palindrome/oyeong011.cpp b/valid-palindrome/oyeong011.cpp new file mode 100644 index 000000000..1bb0ea79c --- /dev/null +++ b/valid-palindrome/oyeong011.cpp @@ -0,0 +1,16 @@ +class Solution { +public: + bool isPalindrome(string s) { + string clean = ""; + for(char c : s) { + if(isalnum(c)) { + clean += tolower(c); + } + } + + string reversed = clean; + reverse(reversed.begin(), reversed.end()); + + return clean == reversed; + } +}; \ No newline at end of file From 5ffa46d3e5955c76aef694e2f668850cf358e14e Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Fri, 6 Dec 2024 11:03:37 +0900 Subject: [PATCH 056/396] top-k-frequent-elements --- top-k-frequent-elements/oyeong011.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 top-k-frequent-elements/oyeong011.cpp diff --git a/top-k-frequent-elements/oyeong011.cpp b/top-k-frequent-elements/oyeong011.cpp new file mode 100644 index 000000000..63fff0689 --- /dev/null +++ b/top-k-frequent-elements/oyeong011.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + const int INF = 987654321; + int temp = INF, ret = 0, cur = 0; + + sort(nums.begin(), nums.end()); + for(int a : nums){ + if(a == temp)continue; + if(temp == INF || temp + 1 == a){ + cur++; temp = a; + } else { + ret = max(ret, cur); + cur = 1; + temp = a; + } + } + ret = max(ret, cur); + return ret; + } +}; \ No newline at end of file From f2027992bafffdafdfcdd85f899721f374b6e52c Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Fri, 6 Dec 2024 11:03:53 +0900 Subject: [PATCH 057/396] house-robber sol --- house-robber/oyeong011.cpp | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 house-robber/oyeong011.cpp diff --git a/house-robber/oyeong011.cpp b/house-robber/oyeong011.cpp new file mode 100644 index 000000000..579136f40 --- /dev/null +++ b/house-robber/oyeong011.cpp @@ -0,0 +1,17 @@ +class Solution { +public: + int rob(vector& nums) { + int n = nums.size(); + if(n == 0)return 0; + if(n == 1)return nums[0]; + if(n == 2)return max(nums[0], nums[1]); + + vector dp(n); + dp[0] = nums[0]; + dp[1] = max(nums[0], nums[1]); + for(int i = 2; i < n; i++){ + dp[i] = max(dp[i - 1], dp[i - 2] + nums[i]); + } + return dp[n - 1]; + } +}; \ No newline at end of file From 6322e95eda9dca4ace778dfb3f6df3985b3c9e58 Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Fri, 6 Dec 2024 11:10:32 +0900 Subject: [PATCH 058/396] longest consecutive sequence sol --- longest-consecutive-sequence/oyeong011.cpp | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 longest-consecutive-sequence/oyeong011.cpp diff --git a/longest-consecutive-sequence/oyeong011.cpp b/longest-consecutive-sequence/oyeong011.cpp new file mode 100644 index 000000000..2c1b9ded4 --- /dev/null +++ b/longest-consecutive-sequence/oyeong011.cpp @@ -0,0 +1,21 @@ +class Solution { +public: + int longestConsecutive(vector& nums) { + const int INF = 987654321; + int temp = INF, ret = 0, cur = 0; + + sort(nums.begin(), nums.end()); + for(int a : nums){ + if(a == temp)continue; + if(temp == INF || temp + 1 == a){ + cur++; temp = a; + } else { + ret = max(ret, cur); + cur = 1; + temp = a; + } + } + ret = max(ret, cur); + return ret; + } +}; \ No newline at end of file From 88165eca453de66f1a700fc7f92987d226055858 Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Fri, 6 Dec 2024 11:21:09 +0900 Subject: [PATCH 059/396] =?UTF-8?q?=EA=B0=9C=ED=96=89=20=EB=AC=B8=EC=9E=90?= =?UTF-8?q?=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/oyeong011.cpp | 2 +- house-robber/oyeong011.cpp | 2 +- longest-consecutive-sequence/oyeong011.cpp | 2 +- top-k-frequent-elements/oyeong011.cpp | 2 +- valid-palindrome/oyeong011.cpp | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/contains-duplicate/oyeong011.cpp b/contains-duplicate/oyeong011.cpp index df718d29c..3a781dbec 100644 --- a/contains-duplicate/oyeong011.cpp +++ b/contains-duplicate/oyeong011.cpp @@ -11,4 +11,4 @@ class Solution { } return false; } -}; \ No newline at end of file +}; diff --git a/house-robber/oyeong011.cpp b/house-robber/oyeong011.cpp index 579136f40..bb108d698 100644 --- a/house-robber/oyeong011.cpp +++ b/house-robber/oyeong011.cpp @@ -14,4 +14,4 @@ class Solution { } return dp[n - 1]; } -}; \ No newline at end of file +}; diff --git a/longest-consecutive-sequence/oyeong011.cpp b/longest-consecutive-sequence/oyeong011.cpp index 2c1b9ded4..4152c4c9b 100644 --- a/longest-consecutive-sequence/oyeong011.cpp +++ b/longest-consecutive-sequence/oyeong011.cpp @@ -18,4 +18,4 @@ class Solution { ret = max(ret, cur); return ret; } -}; \ No newline at end of file +}; diff --git a/top-k-frequent-elements/oyeong011.cpp b/top-k-frequent-elements/oyeong011.cpp index 63fff0689..1326f19da 100644 --- a/top-k-frequent-elements/oyeong011.cpp +++ b/top-k-frequent-elements/oyeong011.cpp @@ -18,4 +18,4 @@ class Solution { ret = max(ret, cur); return ret; } -}; \ No newline at end of file +}; diff --git a/valid-palindrome/oyeong011.cpp b/valid-palindrome/oyeong011.cpp index 1bb0ea79c..9b028a11b 100644 --- a/valid-palindrome/oyeong011.cpp +++ b/valid-palindrome/oyeong011.cpp @@ -13,4 +13,4 @@ class Solution { return clean == reversed; } -}; \ No newline at end of file +}; From ceaff05a39852e1ff3782ef9a6818a418ad8a066 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Fri, 6 Dec 2024 12:36:37 +0900 Subject: [PATCH 060/396] House Robber --- house-robber/EcoFriendlyAppleSu.kt | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 house-robber/EcoFriendlyAppleSu.kt diff --git a/house-robber/EcoFriendlyAppleSu.kt b/house-robber/EcoFriendlyAppleSu.kt new file mode 100644 index 000000000..56c0d3886 --- /dev/null +++ b/house-robber/EcoFriendlyAppleSu.kt @@ -0,0 +1,30 @@ +package leetcode_study + +/** + * DP를 사용한 문제 풀이. + * DP를 사용하지 않고 모든 경우의 수를 계산하여 최대 값을 구하려면 100!에 해당하는 연산이 필요하며, 이는 시간 초과를 초래합니다. + * 시간 복잡도 : O(n) + * -> 주어진 숫자 배열 만큼 반복 진행 + * 공간 복잡도 : O(n) + * -> 숫자 배열만큼의 가중치를 담을 배열 필요 + */ +fun rob(nums: IntArray): Int { + val dp = IntArray(nums.size) + + if (nums.size == 1) { + return nums[0] + } + + if (nums.size == 2) { + return max(nums[0], nums[1]) + } + + dp[0] = nums[0] + dp[1] = nums[1] + dp[2] = nums[2] + dp[0] + + for (i in 3 until nums.size) { + dp[i] = max(dp[i-3], dp[i-2]) + nums[i] + } + return dp.max() +} From 9b2784c9874825110d23aaf46b8fabe7cc4f2a1a Mon Sep 17 00:00:00 2001 From: pmjuu Date: Thu, 5 Dec 2024 22:55:17 -0500 Subject: [PATCH 061/396] feat: solve valid palindrome --- valid-palindrome/pmjuu.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 valid-palindrome/pmjuu.py diff --git a/valid-palindrome/pmjuu.py b/valid-palindrome/pmjuu.py new file mode 100644 index 000000000..83ac4a78e --- /dev/null +++ b/valid-palindrome/pmjuu.py @@ -0,0 +1,22 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + # two pointer + left, right = 0, len(s) - 1 + + while left < right: + # compare only alphanumeric characters + while left < right and not s[left].isalnum(): + left += 1 + while left < right and not s[right].isalnum(): + right -= 1 + + # compare with lowercase + if s[left].lower() != s[right].lower(): + return False + + # move pointers + left += 1 + right -= 1 + + return True + \ No newline at end of file From 69a28ae82dd3da63d8fc79f784438661d43be44e Mon Sep 17 00:00:00 2001 From: pmjuu Date: Thu, 5 Dec 2024 23:00:01 -0500 Subject: [PATCH 062/396] fix: modify line break --- valid-palindrome/pmjuu.py | 1 - 1 file changed, 1 deletion(-) diff --git a/valid-palindrome/pmjuu.py b/valid-palindrome/pmjuu.py index 83ac4a78e..004531ba7 100644 --- a/valid-palindrome/pmjuu.py +++ b/valid-palindrome/pmjuu.py @@ -19,4 +19,3 @@ def isPalindrome(self, s: str) -> bool: right -= 1 return True - \ No newline at end of file From 73b13411c182cbf705400c494017d431135f3489 Mon Sep 17 00:00:00 2001 From: selim-jo Date: Fri, 6 Dec 2024 17:47:28 +0900 Subject: [PATCH 063/396] valid palindrome solution --- valid-palindrome/limlimjo.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 valid-palindrome/limlimjo.js diff --git a/valid-palindrome/limlimjo.js b/valid-palindrome/limlimjo.js new file mode 100644 index 000000000..ccb4b1f49 --- /dev/null +++ b/valid-palindrome/limlimjo.js @@ -0,0 +1,23 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + // 1. 문자열을 다 소문자로 바꾸고, 알파벳/숫자 아닌 거 다 제거 + if (s.length === 1) { + return true; + } else { + let lcLetter = s.toLowerCase().replace(/[^a-z0-9]/g, ''); + //console.log(lcLetter); + + // 2. 문자열이 앞에서 시작할 때와 뒤에서 시작할 때 같으면 true, 아니면 false + if(lcLetter) { + for(let i=0; i Date: Fri, 6 Dec 2024 18:28:46 +0900 Subject: [PATCH 064/396] feat: solve top-k-frequent-elements --- top-k-frequent-elements/GangBean.java | 47 +++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 top-k-frequent-elements/GangBean.java diff --git a/top-k-frequent-elements/GangBean.java b/top-k-frequent-elements/GangBean.java new file mode 100644 index 000000000..17a8cecac --- /dev/null +++ b/top-k-frequent-elements/GangBean.java @@ -0,0 +1,47 @@ +import java.util.*; +import java.util.stream.Collectors; + +class Solution { + public int[] topKFrequent(int[] nums, int k) { + /** + k번째로 많이 등장한 숫자를 구하는 문제. + 구해야 하는 것. + 1. 등장횟수의 순위 + 2. k번째 순위에 해당하는 수의 값 + + 1. 등장 횟수를 구하는 방법: 전체를 순회해 숫자별 등장 횟수를 저장 -> O(N) + 2. 등장 횟수의 순위를 구하는 방법: 등장 횟수에 대해 sort + -> O(MlogM) where N = M(M+1) / 2 + -> logN = logM + log(M+1) + C + -> M = N^(1/2) + -> O(MlogM) = O(N^1/2logN) (??? 여기가 맞는지 모르겠네요..) + 3. 역 인덱스를 구해 매핑되는 수를 구함 -> O(N) + + 전체: O(N) + */ + Map numToCount = new HashMap<>(); + for (int num : nums) { // O(N) + numToCount.put(num, numToCount.getOrDefault(num, 0) + 1); + } + + Map> countToNum = new HashMap<>(); + for (Map.Entry entry: numToCount.entrySet()) { + List numList = countToNum.getOrDefault(entry.getValue(), new ArrayList<>()); + numList.add(entry.getKey()); + countToNum.put(entry.getValue(), numList); + } // O(logN): because sum of all counts is equal to N + + List countRank = countToNum.keySet().stream().sorted(Collections.reverseOrder()).collect(Collectors.toList()); + // O(MlogM) where N = M(M+1) / 2 + + int[] ret = new int[k]; + int idx = 0; + int rank = 0; + while (idx < k) { // O(k) <= O(N) + for (int num : countToNum.get(countRank.get(rank++))) { + ret[idx++] = num; + } + } + return ret; + } +} From a63ea90463684d88c5b6d29708d1a49d52c518b5 Mon Sep 17 00:00:00 2001 From: mintheon Date: Sat, 7 Dec 2024 00:25:26 +0900 Subject: [PATCH 065/396] longest-consecutive-sequence solved --- longest-common-subsequence/mintheon.java | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 longest-common-subsequence/mintheon.java diff --git a/longest-common-subsequence/mintheon.java b/longest-common-subsequence/mintheon.java new file mode 100644 index 000000000..1cebd2166 --- /dev/null +++ b/longest-common-subsequence/mintheon.java @@ -0,0 +1,30 @@ +import java.util.HashSet; +import java.util.Set; + +class Solution { + public int longestConsecutive(int[] nums) { + Set numSet = new HashSet<>(); + + for(int num : nums) { + numSet.add(num); + } + + int longestSize = 0; + + for(int num : numSet) { + if(!numSet.contains(num - 1)) { + int current = num; + int count = 1; + + while(numSet.contains(current + 1)) { + count++; + current++; + } + + longestSize = Math.max(count, longestSize); + } + } + + return longestSize; + } +} From c0339428b1bc8cd013ce046dc2775f0a8f4632c0 Mon Sep 17 00:00:00 2001 From: mintheon Date: Sat, 7 Dec 2024 02:09:23 +0900 Subject: [PATCH 066/396] house-robber solved --- house-robber/mintheon.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 house-robber/mintheon.java diff --git a/house-robber/mintheon.java b/house-robber/mintheon.java new file mode 100644 index 000000000..bc17b3851 --- /dev/null +++ b/house-robber/mintheon.java @@ -0,0 +1,28 @@ +class Solution { + public int rob(int[] nums) { + int[] sums = new int[nums.length]; + + sums[0] = nums[0]; + + if (nums.length > 1) { + sums[1] = nums[1]; + } + + if (nums.length > 2) { + sums[2] = nums[0] + nums[2]; + } + + if (nums.length > 3) { + for (int i = 3; i < nums.length; i++) { + sums[i] = Math.max(nums[i] + sums[i - 2], nums[i] + sums[i - 3]); + } + } + + int max = 0; + for(int sum : sums) { + max = Math.max(sum, max); + } + + return max; + } +} From b5adf9aceee741af822978c6bfc1999263a7c92c Mon Sep 17 00:00:00 2001 From: selim-jo Date: Sat, 7 Dec 2024 11:51:43 +0900 Subject: [PATCH 067/396] top k frequent elements solution --- top-k-frequent-elements/limlimjo.js | 32 +++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 top-k-frequent-elements/limlimjo.js diff --git a/top-k-frequent-elements/limlimjo.js b/top-k-frequent-elements/limlimjo.js new file mode 100644 index 000000000..085bb9cb1 --- /dev/null +++ b/top-k-frequent-elements/limlimjo.js @@ -0,0 +1,32 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + let map = new Map(); // key에는 해당되는 숫자, value에는 해당되는 숫자의 갯수 + + // 숫자별 빈도수 + nums.forEach((num) => { + map.set(num, (map.get(num) || 0) + 1); + }); + + // 결과를 배열로 바꿔주고 내림차순 정렬 + let sortedResult = Array.from(map.entries()).sort((a,b) => b[1] - a[1]); + //console.log(sortedResult); + //console.log(sortedResult.slice(0,k)); + + // k갯수의 숫자 반환 + return sortedResult.slice(0,k).map(item => item[0]); +}; + +// 여기서 위 코드의 시간복잡도와 공간복잡도를 생각해보자... +// 시간복잡도 => O(m log m) ** 더 개선할 방법 찾아보기 +// forEach 통한 배열 순회: 배열의 크기가 n이라고 한다면 O(n) +// sortedResult (정렬): O(m log m) +// k갯수의 숫자 반환: k개 항목에 대해 연산하니까 O(k) + +// 공간복잡도 => O(n) +// map의 크기: 배열의 크기가 n이라고 한다면 O(n) +// sortedResult: O(m) +// k개 숫자 저장: O(k) From c4f478575991965b43a564772ec4cabc7a889166 Mon Sep 17 00:00:00 2001 From: GangBean Date: Sat, 7 Dec 2024 11:55:24 +0900 Subject: [PATCH 068/396] feat: solve longest-consecutive-sequence --- longest-consecutive-sequence/GangBean.java | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 longest-consecutive-sequence/GangBean.java diff --git a/longest-consecutive-sequence/GangBean.java b/longest-consecutive-sequence/GangBean.java new file mode 100644 index 000000000..c0b7beb86 --- /dev/null +++ b/longest-consecutive-sequence/GangBean.java @@ -0,0 +1,23 @@ +import java.util.*; +import java.util.stream.Collectors; + +class Solution { + public int longestConsecutive(int[] nums) { + Set set = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + + int maxLength = 0; + for (int num: nums) { + // 각 숫자에 대해 최초 값이 가능하면, 즉 num-1이 존재하지 않으면 최대 length 구하기 + if (set.contains(num - 1)) continue; + int length = 1; + int start = num; + while (set.contains(start + 1)) { + length++; + start++; + } + maxLength = Math.max(length, maxLength); + } + + return maxLength; + } +} From 6f733c801f65ceda2e5edc915a3ab22a9ddbe142 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Sat, 7 Dec 2024 15:14:38 +0900 Subject: [PATCH 069/396] feat: [Week 01-5] solve house-robber --- house-robber/Chaedie.py | 103 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 house-robber/Chaedie.py diff --git a/house-robber/Chaedie.py b/house-robber/Chaedie.py new file mode 100644 index 000000000..5a5922022 --- /dev/null +++ b/house-robber/Chaedie.py @@ -0,0 +1,103 @@ +''' +Solution: + 스스로 풀지 못해 학습만 진행했습니다. + 다음 기회에 다시 풀어보도록 하겠습니다. +''' +class Solution: + def rob(self, nums: List[int]) -> int: + prev, curr = 0, 0 + for num in nums: + prev, curr = curr, max(num + prev, curr) + + return curr + + +# class Solution: + # ''' + # 4. 달레의 코드 풀이 - DP, prev, curr + # O(n) time + # O(1) space + # ''' + + # # 달레의 코드 풀이 - DP, prev, cur + + # def rob(self, nums: List[int]) -> int: + # prev, curr = 0, 0 + # for num in nums: + # prev, curr = curr, max(num + prev, curr) + + # return curr + + # ''' + # 3. 달레의 코드 풀이 - DP + # [1,2,3,1] + # [1, 2, 3, 1] + # DP:[0, 1, 2, 4, 4] + # MAX(1 + DP[2], DP[1]) = MAX(1 + 2, 4) = 4 + # ''' + # # 달레의 코드 풀이 - DP + # # def rob(self, nums: List[int]) -> int: + # # dp = [0] * (len(nums) + 1) + # # dp[1] = nums[0] + # # for n in range(2,len(nums) + 1): + # # dp[n] = max(nums[n - 1] + dp[n - 2], dp[n - 1]) + # # return dp[-1] + # ''' + # 2. 달레의 코드 풀이 - 재귀, 메모이제이션 + # time: O(n) + # space: O(n) + # ''' + # # 달레의 코드 풀이 - 재귀, 메모이제이션 + # # def rob(self, nums: List[int]) -> int: + # # memo = {} + + # # def dfs(start): + # # if start in memo: + # # return memo[start] + # # if not start < len(nums): + # # memo[start] = 0 + # # else: + # # memo[start] = max(nums[start] + dfs(start + 2), dfs(start + 1)) + # # return memo[start] + # # return dfs(0) + # ''' + # 1. 달레의 코드 풀이 - 재귀 + # time: O(2^n) + # space: O(n) + + # F([1,2,3,1]) => MAX(1 + F([3,1], f([2,3,1]))) + # F([3,1]) => MAX(3 + F([]), F([1])) + # F([]) => 0 + # F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1 + # F([]) => 0 + # F([]) => 0 + # F([2,3,1]) => MAX(2 + F([1]), F([3,1])) + # F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1 + # F([]) => 0 + # F([]) => 0 + # F([3,1]) => MAX(3 + F([]), F([1])) + # F([]) => 0 + # F([1]) => MAX(1 + F([]), F([])) => MAX(1 + 0, 0) => 1 + # F([]) => 0 + # F([]) => 0 + # 재귀가 불필요하게 반복되고 있다. + # 메모이제이션으로 기억해두면 반복은 스킵할 수 있다. + # ''' + # # 달레의 코드 풀이 - 재귀 + # # def rob(self, nums: List[int]) -> int: + + # # def dfs(start): + # # if not start < len(nums): + # # return 0 + # # return max(nums[start] + dfs(start + 2), dfs(start + 1)) + # # return dfs(0) + + # # neetcode 풀이 - DP, 이해안됨... + # # def rob(self, nums: List[int]) -> int: + # # rob1, rob2 = 0, 0 + # # # [rob1, rob2, n, n+1, ...] + # # for n in nums: + # # temp = max(n + rob1, rob2) + # # rob1 = rob2 + # # rob2 = temp + # # return rob2 \ No newline at end of file From a8abffa37dabc16e4fbaf78028a3ae047cebb36c Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Sat, 7 Dec 2024 15:15:30 +0900 Subject: [PATCH 070/396] fix: add eol --- house-robber/Chaedie.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/house-robber/Chaedie.py b/house-robber/Chaedie.py index 5a5922022..265ff1c7e 100644 --- a/house-robber/Chaedie.py +++ b/house-robber/Chaedie.py @@ -100,4 +100,4 @@ def rob(self, nums: List[int]) -> int: # # temp = max(n + rob1, rob2) # # rob1 = rob2 # # rob2 = temp - # # return rob2 \ No newline at end of file + # # return rob2 From bcb35c2af6e06995c2b52050b57adf5aa8522bd5 Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Sun, 8 Dec 2024 00:33:49 +0900 Subject: [PATCH 071/396] add solution: Valid Palindrome #220 --- valid-palindrome/donghyeon95.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 valid-palindrome/donghyeon95.java diff --git a/valid-palindrome/donghyeon95.java b/valid-palindrome/donghyeon95.java new file mode 100644 index 000000000..ced3edc7a --- /dev/null +++ b/valid-palindrome/donghyeon95.java @@ -0,0 +1,16 @@ +/* 첫 시도 + leetCode 기준 18ms + */ + +class Solution { + public boolean isPalindrome(String s) { + // 1. remove non-alphanumeric using regex + String alphanumeric = s.replaceAll("[^a-zA-Z0-9]", ""); + + // 2. change lowerCase + String lowerCase = alphanumeric.toLowerCase(); + + // 3. compare reverse String + return lowerCase.contentEquals(new StringBuffer(lowerCase).reverse()); + } +} \ No newline at end of file From fa9d5064aa5824d09f744be7f8262f540e7d494c Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Sun, 8 Dec 2024 00:40:17 +0900 Subject: [PATCH 072/396] =?UTF-8?q?fix:=20=EA=B0=9C=ED=96=89=20=EB=AC=B8?= =?UTF-8?q?=EC=9E=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/donghyeon95.java | 3 ++- valid-palindrome/donghyeon95.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/contains-duplicate/donghyeon95.java b/contains-duplicate/donghyeon95.java index f4076156d..82d9267b1 100644 --- a/contains-duplicate/donghyeon95.java +++ b/contains-duplicate/donghyeon95.java @@ -27,4 +27,5 @@ public boolean containsDuplicate(int[] nums) { return false; } -} \ No newline at end of file +} + diff --git a/valid-palindrome/donghyeon95.java b/valid-palindrome/donghyeon95.java index ced3edc7a..68a2a42fa 100644 --- a/valid-palindrome/donghyeon95.java +++ b/valid-palindrome/donghyeon95.java @@ -13,4 +13,5 @@ public boolean isPalindrome(String s) { // 3. compare reverse String return lowerCase.contentEquals(new StringBuffer(lowerCase).reverse()); } -} \ No newline at end of file +} + From 5f152939b0023fc336bcef105f50c6de1588882f Mon Sep 17 00:00:00 2001 From: Real-Reason Date: Sun, 8 Dec 2024 01:26:17 +0900 Subject: [PATCH 073/396] feat: contains-duplicate solve --- contains-duplicate/Real-Reason.kt | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 contains-duplicate/Real-Reason.kt diff --git a/contains-duplicate/Real-Reason.kt b/contains-duplicate/Real-Reason.kt new file mode 100644 index 000000000..599bfaa90 --- /dev/null +++ b/contains-duplicate/Real-Reason.kt @@ -0,0 +1,10 @@ +package leetcode_study + +class Solution { + fun containsDuplicate(nums: IntArray): Boolean { + val size = nums.size + val numsToSet = nums.toSet() + + return size != numsToSet.size + } +} \ No newline at end of file From f9c216ca0624f58d58b2fffae7833c5d67662fad Mon Sep 17 00:00:00 2001 From: kdh-92 Date: Sun, 8 Dec 2024 07:06:51 +0900 Subject: [PATCH 074/396] solve : #237 (Top K Frequent Elements) with Java --- top-k-frequent-elements/kdh-92.java | 82 +++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 top-k-frequent-elements/kdh-92.java diff --git a/top-k-frequent-elements/kdh-92.java b/top-k-frequent-elements/kdh-92.java new file mode 100644 index 000000000..3759619e9 --- /dev/null +++ b/top-k-frequent-elements/kdh-92.java @@ -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 frequencyMap = new HashMap<>(); + + for (int num : nums) { + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); + } + + PriorityQueue> minHeap = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue)); + + for (Map.Entry 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 frequencyMap = new HashMap<>(); + for (int num : nums) { + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); + } + + List[] 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 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(); + } +} From 8436024e501448afce70d2221f85c0601e201d07 Mon Sep 17 00:00:00 2001 From: mintheon Date: Sun, 8 Dec 2024 13:49:07 +0900 Subject: [PATCH 075/396] =?UTF-8?q?longest-consecutive-sequence=EB=A1=9C?= =?UTF-8?q?=20=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../mintheon.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {longest-common-subsequence => longest-consecutive-sequence}/mintheon.java (100%) diff --git a/longest-common-subsequence/mintheon.java b/longest-consecutive-sequence/mintheon.java similarity index 100% rename from longest-common-subsequence/mintheon.java rename to longest-consecutive-sequence/mintheon.java From 3d815af51724a0c34da3cadf503f6b7559ac0dda Mon Sep 17 00:00:00 2001 From: mintheon Date: Sun, 8 Dec 2024 13:52:46 +0900 Subject: [PATCH 076/396] =?UTF-8?q?contains-duplicate=20Set=20=EB=B0=A9?= =?UTF-8?q?=EC=8B=9D=EC=9C=BC=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/mintheon.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/contains-duplicate/mintheon.java b/contains-duplicate/mintheon.java index 1af3d32f8..cb91a7b41 100644 --- a/contains-duplicate/mintheon.java +++ b/contains-duplicate/mintheon.java @@ -1,13 +1,14 @@ -import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; class Solution { public boolean containsDuplicate(int[] nums) { - Arrays.sort(nums); - for(int i = 1; i < nums.length; i++) { - if(nums[i] == nums[i - 1]) { - return true; - } + Set numSet = new HashSet(); + + for(int num : nums) { + numSet.add(num); } - return false; + + return numSet.size() != nums.length; } } From 1907c3cdca074b285978beab3093ef65163b5bd5 Mon Sep 17 00:00:00 2001 From: Paik Date: Sun, 8 Dec 2024 17:02:47 +0900 Subject: [PATCH 077/396] feat: 217.Contains Duplicate --- contains-duplicate/ganu.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 contains-duplicate/ganu.js diff --git a/contains-duplicate/ganu.js b/contains-duplicate/ganu.js new file mode 100644 index 000000000..deeb8c753 --- /dev/null +++ b/contains-duplicate/ganu.js @@ -0,0 +1,12 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function (nums) { + const set = new Set(nums); + + return set.size !== nums.length; +}; From c9407bbd9a4ae56d5dab1ea0acb8aa124d254c47 Mon Sep 17 00:00:00 2001 From: Paik Date: Sun, 8 Dec 2024 17:15:06 +0900 Subject: [PATCH 078/396] fix: Change file name --- contains-duplicate/{ganu.js => gwbaik9717.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{ganu.js => gwbaik9717.js} (100%) diff --git a/contains-duplicate/ganu.js b/contains-duplicate/gwbaik9717.js similarity index 100% rename from contains-duplicate/ganu.js rename to contains-duplicate/gwbaik9717.js From 3ae9ff72ffd63f94b786bd7ba537537414a80614 Mon Sep 17 00:00:00 2001 From: Minji Ko Date: Sun, 8 Dec 2024 18:20:01 +0900 Subject: [PATCH 079/396] feat: contains duplicate --- contains-duplicate/minji-go.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 contains-duplicate/minji-go.java diff --git a/contains-duplicate/minji-go.java b/contains-duplicate/minji-go.java new file mode 100644 index 000000000..7fe2accfb --- /dev/null +++ b/contains-duplicate/minji-go.java @@ -0,0 +1,17 @@ +import java.util.HashSet; +import java.util.Set; + +class Solution { + public boolean containsDuplicate(int[] nums) { + Set count = new HashSet<>(); + boolean answer = false; + for(int num : nums){ + if(count.contains(num)) { + answer = true; + break; + } + count.add(num); + } + return answer; + } +} \ No newline at end of file From 407b10eef841c8b1690375388f6b55fbed678b7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=81=EC=9E=AC?= Date: Sun, 8 Dec 2024 21:10:25 +0900 Subject: [PATCH 080/396] add: solve #217 Contains Duplicate with ts --- contains-duplicate/YJason-K.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 contains-duplicate/YJason-K.ts diff --git a/contains-duplicate/YJason-K.ts b/contains-duplicate/YJason-K.ts new file mode 100644 index 000000000..4b14b86db --- /dev/null +++ b/contains-duplicate/YJason-K.ts @@ -0,0 +1,17 @@ +/** + * Set 자료구조를 사용하여 중복 확인 (시간 복잡도: O(n) ) + * @param nums 중복 검사할 숫자 배열 + * @returns boolean 중복 여부 + */ + +function containsDuplicate(nums: number[]): boolean { + let unique: Set = new Set([]); + for (const num of nums) { + if (unique.has(num)) { + return true + } else { + unique.add(num) + } + } + return false; +}; \ No newline at end of file From 4d964a9969488e6eb73259a139b6da2b0840ef41 Mon Sep 17 00:00:00 2001 From: Minji Ko Date: Sun, 8 Dec 2024 23:00:13 +0900 Subject: [PATCH 081/396] feat: valid palindrome --- valid-palindrome/minji-go.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 valid-palindrome/minji-go.java diff --git a/valid-palindrome/minji-go.java b/valid-palindrome/minji-go.java new file mode 100644 index 000000000..7973fd726 --- /dev/null +++ b/valid-palindrome/minji-go.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isPalindrome(String s) { + String regex ="[^A-Za-z0-9]"; + String palindrome = s.replaceAll(regex,"").toLowerCase(); + + boolean answer = true; + for(int i=0; i Date: Mon, 9 Dec 2024 00:10:51 +0900 Subject: [PATCH 082/396] contains-duplicate --- contains-duplicate/jejufather.cpp | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 contains-duplicate/jejufather.cpp diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp new file mode 100644 index 000000000..2b2418ea6 --- /dev/null +++ b/contains-duplicate/jejufather.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +bool containsDuplicate(int* nums, int numsSize) { + char* pflag = (char*)malloc(1000000001); + char* mflag = (char*)malloc(1000000001); + memset(pflag, 0, 1000000001); + memset(mflag, 0, 1000000001); + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < 0) { + if (mflag[-nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + mflag[-nums[i]] = 1; + } + else { + if (pflag[nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + pflag[nums[i]] = 1; + } + } + free(pflag); + free(mflag); + return false; +} + +void main(void) { + int test[100001] = {0}; + printf("%d\n", containsDuplicate(test, 1)); +} \ No newline at end of file From 7785c4537b1c3bcd6bcce45ed59a491084befd47 Mon Sep 17 00:00:00 2001 From: oyeong011 Date: Mon, 9 Dec 2024 00:14:11 +0900 Subject: [PATCH 083/396] top-k-frequent sol --- top-k-frequent-elements/oyeong011.cpp | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/top-k-frequent-elements/oyeong011.cpp b/top-k-frequent-elements/oyeong011.cpp index 1326f19da..7abe2cfad 100644 --- a/top-k-frequent-elements/oyeong011.cpp +++ b/top-k-frequent-elements/oyeong011.cpp @@ -1,21 +1,16 @@ class Solution { public: - int longestConsecutive(vector& nums) { - const int INF = 987654321; - int temp = INF, ret = 0, cur = 0; + vector topKFrequent(vector& nums, int k) { + map mp; + priority_queue> pq; + vector ans; - sort(nums.begin(), nums.end()); - for(int a : nums){ - if(a == temp)continue; - if(temp == INF || temp + 1 == a){ - cur++; temp = a; - } else { - ret = max(ret, cur); - cur = 1; - temp = a; - } - } - ret = max(ret, cur); - return ret; + for(auto b : nums) mp[b]++; + + for(auto p : mp) pq.push({p.second, p.first}); + + while(k--)ans.push_back(pq.top().second), pq.pop(); + + return ans; } }; From cc905f54fa2ad90e2a2830069641ea1b252acfb3 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:29:27 +0900 Subject: [PATCH 084/396] contains-duplicate --- contains-duplicate/jejufather.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp index 2b2418ea6..81221d523 100644 --- a/contains-duplicate/jejufather.cpp +++ b/contains-duplicate/jejufather.cpp @@ -30,6 +30,7 @@ bool containsDuplicate(int* nums, int numsSize) { return false; } + void main(void) { int test[100001] = {0}; printf("%d\n", containsDuplicate(test, 1)); From c3e92cfecb4ecf6e9945af6e1fcc1063569b5f05 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:31:46 +0900 Subject: [PATCH 085/396] Delete 3sum/csucom.py --- 3sum/csucom.py | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 3sum/csucom.py diff --git a/3sum/csucom.py b/3sum/csucom.py deleted file mode 100644 index 9def7cf98..000000000 --- a/3sum/csucom.py +++ /dev/null @@ -1,3 +0,0 @@ -''' - test code -''' \ No newline at end of file From 7ed155864f2fa6c8da8a4a78de0ed7a13215942c Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:36:08 +0900 Subject: [PATCH 086/396] contains-duplicate --- contains-duplicate/jejufather.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp index 81221d523..61544a620 100644 --- a/contains-duplicate/jejufather.cpp +++ b/contains-duplicate/jejufather.cpp @@ -30,8 +30,7 @@ bool containsDuplicate(int* nums, int numsSize) { return false; } - void main(void) { int test[100001] = {0}; printf("%d\n", containsDuplicate(test, 1)); -} \ No newline at end of file +} From 85aa203fe129599b815115462af85b7916e9cbe3 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:48:05 +0900 Subject: [PATCH 087/396] contains-duplicate --- contains-duplicate/csucom.cpp | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 contains-duplicate/csucom.cpp diff --git a/contains-duplicate/csucom.cpp b/contains-duplicate/csucom.cpp new file mode 100644 index 000000000..61544a620 --- /dev/null +++ b/contains-duplicate/csucom.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +bool containsDuplicate(int* nums, int numsSize) { + char* pflag = (char*)malloc(1000000001); + char* mflag = (char*)malloc(1000000001); + memset(pflag, 0, 1000000001); + memset(mflag, 0, 1000000001); + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < 0) { + if (mflag[-nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + mflag[-nums[i]] = 1; + } + else { + if (pflag[nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + pflag[nums[i]] = 1; + } + } + free(pflag); + free(mflag); + return false; +} + +void main(void) { + int test[100001] = {0}; + printf("%d\n", containsDuplicate(test, 1)); +} From e48bda1a65ee732e57500a5e6e2ed98ce5a1f474 Mon Sep 17 00:00:00 2001 From: kdh-92 Date: Mon, 9 Dec 2024 07:11:25 +0900 Subject: [PATCH 088/396] solve : #240 (Longest Consecutive Sequence) with Java --- longest-consecutive-sequence/kdh-92.java | 61 ++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 longest-consecutive-sequence/kdh-92.java diff --git a/longest-consecutive-sequence/kdh-92.java b/longest-consecutive-sequence/kdh-92.java new file mode 100644 index 000000000..7b548d43a --- /dev/null +++ b/longest-consecutive-sequence/kdh-92.java @@ -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 uniqueNums = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + // int result = 0; + + // for (int num : nums) { + // 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 hm = new HashMap<>(); + + for(int i=0; i Date: Mon, 9 Dec 2024 08:13:32 +0900 Subject: [PATCH 089/396] feat: Upload contains-duplicate solution (typescript) --- contains-duplicate/mike2ox.ts | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 contains-duplicate/mike2ox.ts diff --git a/contains-duplicate/mike2ox.ts b/contains-duplicate/mike2ox.ts new file mode 100644 index 000000000..62cb625c4 --- /dev/null +++ b/contains-duplicate/mike2ox.ts @@ -0,0 +1,4 @@ +function containsDuplicate(nums: number[]): boolean { + const set = new Set(nums); + return set.size !== nums.length; +} From 622ff7aed7fcaab2fd5b5aed6535ea7675a115b1 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 09:19:37 +0900 Subject: [PATCH 090/396] Delete contains-duplicate/jejufather.cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 올바르지 않은 파일명을 가진 파일 삭제 --- contains-duplicate/jejufather.cpp | 36 ------------------------------- 1 file changed, 36 deletions(-) delete mode 100644 contains-duplicate/jejufather.cpp diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp deleted file mode 100644 index 61544a620..000000000 --- a/contains-duplicate/jejufather.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include -#include - -bool containsDuplicate(int* nums, int numsSize) { - char* pflag = (char*)malloc(1000000001); - char* mflag = (char*)malloc(1000000001); - memset(pflag, 0, 1000000001); - memset(mflag, 0, 1000000001); - for (int i = 0; i < numsSize; ++i) { - if (nums[i] < 0) { - if (mflag[-nums[i]] == 1) { - free(pflag); - free(mflag); - return true; - } - mflag[-nums[i]] = 1; - } - else { - if (pflag[nums[i]] == 1) { - free(pflag); - free(mflag); - return true; - } - pflag[nums[i]] = 1; - } - } - free(pflag); - free(mflag); - return false; -} - -void main(void) { - int test[100001] = {0}; - printf("%d\n", containsDuplicate(test, 1)); -} From aef971c7ac6b286e43c15acb55b5d0a55a02b790 Mon Sep 17 00:00:00 2001 From: csucom Date: Mon, 9 Dec 2024 09:55:01 +0900 Subject: [PATCH 091/396] contains-duplicate solution --- contains-duplicate/csucom.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contains-duplicate/csucom.cpp b/contains-duplicate/csucom.cpp index 61544a620..1fcb4171e 100644 --- a/contains-duplicate/csucom.cpp +++ b/contains-duplicate/csucom.cpp @@ -1,4 +1,4 @@ -#include +//#include #include #include @@ -30,7 +30,7 @@ bool containsDuplicate(int* nums, int numsSize) { return false; } -void main(void) { - int test[100001] = {0}; - printf("%d\n", containsDuplicate(test, 1)); -} +// void main(void) { +// int test[100001] = {0}; +// printf("%d\n", containsDuplicate(test, 1)); +// } From 29a569b6fe347d345a64a39ac932317bae36a411 Mon Sep 17 00:00:00 2001 From: Changhyun Lee Date: Mon, 9 Dec 2024 10:18:19 +0900 Subject: [PATCH 092/396] ADD : contains-duplicate/heypaprika.py --- contains-duplicate/heypaprika.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 contains-duplicate/heypaprika.py diff --git a/contains-duplicate/heypaprika.py b/contains-duplicate/heypaprika.py new file mode 100644 index 000000000..2aa679a9b --- /dev/null +++ b/contains-duplicate/heypaprika.py @@ -0,0 +1,10 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + num_dict = {} + for num in nums: + if num in num_dict: + return True + else: + num_dict[num] = 1 + return False + From 5f1eefe00b08e20d7df594edcdbdb9ffc2d4d283 Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 10:40:14 +0900 Subject: [PATCH 093/396] 217. Contains Duplicate --- contains-duplicate/y00eunji.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 contains-duplicate/y00eunji.js diff --git a/contains-duplicate/y00eunji.js b/contains-duplicate/y00eunji.js new file mode 100644 index 000000000..85439fb04 --- /dev/null +++ b/contains-duplicate/y00eunji.js @@ -0,0 +1,9 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + // set에 넣어 중복을 줄이고 길이를 비교한다. + + return new Set(nums).size !== nums.length; +}; From 867cdbec0f45fe69cf6a25fca86e5dfa6d424df4 Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 11:12:43 +0900 Subject: [PATCH 094/396] 125. Valid Palindrome --- valid-palindrome/y00eunji.js | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 valid-palindrome/y00eunji.js diff --git a/valid-palindrome/y00eunji.js b/valid-palindrome/y00eunji.js new file mode 100644 index 000000000..c808a69a8 --- /dev/null +++ b/valid-palindrome/y00eunji.js @@ -0,0 +1,10 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + const filtered = s.toLowerCase().replace(/[^a-zA-Z0-9]/g, ''); + const reversed = filtered.split('').reverse().join(''); + + return filtered === reversed; +}; \ No newline at end of file From d5c86da18c29ed07d3dc8780ce38f4f38db568ab Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 11:14:30 +0900 Subject: [PATCH 095/396] 125. Valid Palindrome --- valid-palindrome/y00eunji.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/valid-palindrome/y00eunji.js b/valid-palindrome/y00eunji.js index c808a69a8..95df65d1d 100644 --- a/valid-palindrome/y00eunji.js +++ b/valid-palindrome/y00eunji.js @@ -7,4 +7,4 @@ var isPalindrome = function(s) { const reversed = filtered.split('').reverse().join(''); return filtered === reversed; -}; \ No newline at end of file +}; From 11e43f8032656d9782c8d7cb81614bd2a66118a9 Mon Sep 17 00:00:00 2001 From: Paik Date: Mon, 9 Dec 2024 11:26:59 +0900 Subject: [PATCH 096/396] feat: 220.Valid Palindrome --- valid-palindrome/gwbaik9717.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 valid-palindrome/gwbaik9717.js diff --git a/valid-palindrome/gwbaik9717.js b/valid-palindrome/gwbaik9717.js new file mode 100644 index 000000000..890929a89 --- /dev/null +++ b/valid-palindrome/gwbaik9717.js @@ -0,0 +1,17 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function (s) { + const normalize = (s) => { + return s.toLowerCase().replace(/[^a-z0-9]/g, ""); + }; + + const normalized = normalize(s); + const reversed = normalized.split("").reverse().join(""); + + return normalized === reversed; +}; From 116161f1fb627b69d9c0de37ea5404a13b3ef079 Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 11:39:54 +0900 Subject: [PATCH 097/396] 347. Top K Frequent Elements --- top-k-frequent-elements/y00eunji.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 top-k-frequent-elements/y00eunji.js diff --git a/top-k-frequent-elements/y00eunji.js b/top-k-frequent-elements/y00eunji.js new file mode 100644 index 000000000..9e634ee86 --- /dev/null +++ b/top-k-frequent-elements/y00eunji.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + // 1. nums 배열을 순회하여 각 숫자의 빈도를 계산하고 obj 객체에 저장 + const obj = nums.reduce((arr, idx) => { + arr[idx] = (arr[idx] || 0) + 1; + return arr; + }, {}); + + // 2. obj 객체의 키-값 쌍을 배열로 변환하고, 값을 기준으로 내림차순 정렬, k개 추출 + const frequentArr = Object.entries(obj) + .sort(([, valueA], [, valueB]) => valueB - valueA) + .slice(0, k) + .map(([key]) => +key); + + return frequentArr; +}; From fbe1ac8ba8534b308beae57106cc8eba540765b8 Mon Sep 17 00:00:00 2001 From: Changhyun Lee Date: Mon, 9 Dec 2024 11:43:16 +0900 Subject: [PATCH 098/396] ADD : #220 #237 #240 #264 by heypaprika --- house-robber/heypaprika.py | 18 ++++++++++++++++++ longest-consecutive-sequence/heypaprika.py | 21 +++++++++++++++++++++ top-k-frequent-elements/heypaprika.py | 15 +++++++++++++++ valid-palindrome/heypaprika.py | 14 ++++++++++++++ 4 files changed, 68 insertions(+) create mode 100644 house-robber/heypaprika.py create mode 100644 longest-consecutive-sequence/heypaprika.py create mode 100644 top-k-frequent-elements/heypaprika.py create mode 100644 valid-palindrome/heypaprika.py diff --git a/house-robber/heypaprika.py b/house-robber/heypaprika.py new file mode 100644 index 000000000..583399a1e --- /dev/null +++ b/house-robber/heypaprika.py @@ -0,0 +1,18 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + a = [0] * len(nums) + + if len(nums) == 1: + return nums[0] + elif len(nums) == 2: + return max(nums[0], nums[1]) + + a[0] = nums[0] + a[1] = nums[1] + a[2] = max(a[0] + nums[2], a[1]) + + for i in range(3, len(nums)): + a[i] = max(a[i-3], a[i-2]) + nums[i] + + return max(a) + diff --git a/longest-consecutive-sequence/heypaprika.py b/longest-consecutive-sequence/heypaprika.py new file mode 100644 index 000000000..a1f618d9a --- /dev/null +++ b/longest-consecutive-sequence/heypaprika.py @@ -0,0 +1,21 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + nums = sorted(list(set(nums))) + if len(nums) == 0: + return 0 + elif len(nums) == 1: + return 1 + cur_long = 1 + longest = 1 + for i, num in enumerate(nums): + if i == 0: + continue + else: + if nums[i-1] + 1 == nums[i]: + cur_long += 1 + if longest < cur_long: + longest = cur_long + else: + cur_long = 1 + return longest + diff --git a/top-k-frequent-elements/heypaprika.py b/top-k-frequent-elements/heypaprika.py new file mode 100644 index 000000000..bfd5996a8 --- /dev/null +++ b/top-k-frequent-elements/heypaprika.py @@ -0,0 +1,15 @@ +import heapq +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + + num_dict = {} + for num in nums: + num_dict[num] = num_dict.get(num, 0) + 1 + heap = [] + for k_, v in num_dict.items(): + heapq.heappush(heap, [-v, k_]) + ans = [] + for i in range(k): + ans.append(heapq.heappop(heap)[1]) + return ans + diff --git a/valid-palindrome/heypaprika.py b/valid-palindrome/heypaprika.py new file mode 100644 index 000000000..41272ff9d --- /dev/null +++ b/valid-palindrome/heypaprika.py @@ -0,0 +1,14 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + s = "".join(s.lower().split(" ")) + new_s = "" + for item in s: + if (ord("a") <= ord(item) <= ord("z")) or (ord("0") <= ord(item) <= ord("9")): + new_s += item + output = True + for i in range(len(new_s) // 2): + if new_s[i] != new_s[-i-1]: + output = False + break + return output + From 8cc191ce7124fee0837b2b1961bf5c9bbe219607 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Mon, 9 Dec 2024 11:45:12 +0900 Subject: [PATCH 099/396] Add placeholder file for 'Contains Duplicate' problem --- contains-duplicate/KwonNayeon.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 contains-duplicate/KwonNayeon.py diff --git a/contains-duplicate/KwonNayeon.py b/contains-duplicate/KwonNayeon.py new file mode 100644 index 000000000..e69de29bb From 5dd362874c4080668a5b9e6acd649b5cf294a160 Mon Sep 17 00:00:00 2001 From: Minji Go Date: Mon, 9 Dec 2024 12:10:59 +0900 Subject: [PATCH 100/396] =?UTF-8?q?refactor:=20=EA=B0=9C=ED=96=89=EB=AC=B8?= =?UTF-8?q?=EC=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/minji-go.java | 5 +---- valid-palindrome/minji-go.java | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/contains-duplicate/minji-go.java b/contains-duplicate/minji-go.java index 7fe2accfb..a69cdcac0 100644 --- a/contains-duplicate/minji-go.java +++ b/contains-duplicate/minji-go.java @@ -1,6 +1,3 @@ -import java.util.HashSet; -import java.util.Set; - class Solution { public boolean containsDuplicate(int[] nums) { Set count = new HashSet<>(); @@ -14,4 +11,4 @@ public boolean containsDuplicate(int[] nums) { } return answer; } -} \ No newline at end of file +} diff --git a/valid-palindrome/minji-go.java b/valid-palindrome/minji-go.java index 7973fd726..4001f0d51 100644 --- a/valid-palindrome/minji-go.java +++ b/valid-palindrome/minji-go.java @@ -12,4 +12,4 @@ public boolean isPalindrome(String s) { } return answer; } -} \ No newline at end of file +} From b0e37bcb4102fb1d690438dcc232829a6646db51 Mon Sep 17 00:00:00 2001 From: mike2ox Date: Mon, 9 Dec 2024 13:21:02 +0900 Subject: [PATCH 101/396] docs: Add comments to problem solving --- contains-duplicate/mike2ox.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/contains-duplicate/mike2ox.ts b/contains-duplicate/mike2ox.ts index 62cb625c4..59fb3bda7 100644 --- a/contains-duplicate/mike2ox.ts +++ b/contains-duplicate/mike2ox.ts @@ -1,4 +1,16 @@ +/** + * Source: https://leetcode.com/problems/contains-duplicate/ + * 풀이방법: Set을 이용하여 중복된 값이 있는지 확인 + * 시간복잡도: O(n) + * 공간복잡도: O(n) + * + * 생각나는 풀이방법 + * 1. 단순하게 sorted를 이용하여 이전값과 비교하여 중복된 값이 있는지 확인 + * 2. 정렬하지 않고 nums의 길이만큼의 배열을 만들어서 중복된 값이 있는지 저장하면서 확인 + */ function containsDuplicate(nums: number[]): boolean { + // 중복된 값이 없는 자료구조 Set 활용 const set = new Set(nums); + // Set의 size와 nums의 length를 비교하여 중복된 값이 있는지 확인 return set.size !== nums.length; } From 60d362f41800793bf439131708bcb7d8f6426033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=81=EC=9E=AC?= Date: Mon, 9 Dec 2024 13:26:01 +0900 Subject: [PATCH 102/396] add: solve #220 Valid Palindrome with ts --- valid-palindrome/YJason-K.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 valid-palindrome/YJason-K.ts diff --git a/valid-palindrome/YJason-K.ts b/valid-palindrome/YJason-K.ts new file mode 100644 index 000000000..b03871a5d --- /dev/null +++ b/valid-palindrome/YJason-K.ts @@ -0,0 +1,32 @@ +/** + * 문자열을 알파벳 대문자를 소문자로 변환 및 숫자만 남기는 변환 유틸 + * - 시간 복잡도: O(n) (입력된 문자열의 길이에 비례) + * + * @param {string} s - 정제할 물자열 + * @returns {string} - 소문자 알파벳과 숫자로 이루어진 문자열 + */ +const refinePhrase = (s:string) : string => s.toLowerCase().replace(/[^a-z0-9]/g, ''); + + +/** + * 문자열을 정제후 palindrome 여부 확인 하는 함수 + * - 시간 복잡도: O(n) (문자열 정제 + 투 포인터 알고리즘) + * + * @param {string} s palindrome 여부를 확인할 문자열 + * @returns {boolean} palindrome 여부 + */ +function isPalindrome(s: string): boolean { + const refined = refinePhrase(s); + + // two pointer를 활용한 palindrome 확인 O(n) + let left = 0, right = refined.length - 1; + while (left < right) { + if (refined[left] !== refined[right]) { + return false; + } + left++; + right--; + } + + return true; +} From dd7c18f7071317b4c8d6b62f9e4c659ac13c1570 Mon Sep 17 00:00:00 2001 From: mike2ox Date: Mon, 9 Dec 2024 14:06:25 +0900 Subject: [PATCH 103/396] feat: Upload valid-palindrome solution (typescript) --- valid-palindrome/mike2ox.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 valid-palindrome/mike2ox.ts diff --git a/valid-palindrome/mike2ox.ts b/valid-palindrome/mike2ox.ts new file mode 100644 index 000000000..5ad7c9d5f --- /dev/null +++ b/valid-palindrome/mike2ox.ts @@ -0,0 +1,29 @@ +/** + * Source: https://leetcode.com/problems/valid-palindrome/ + * 풀이방법: 문자열을 조건에 맞게 정제한 후 reverse하여 비교 + * 시간복잡도: O(n) + * 공간복잡도: O(n) + * + * 생각나는 풀이방법 + * 1. 정규식을 이용하여 문자열을 정제한 후 reverse하여 비교 => 정규식 작성을 못해서 배제 + * 2. 문자열을 순회하면서 조건에 맞는 문자만 배열에 저장한 후 reverse하여 비교 + */ +function isPalindrome(s: string): boolean { + // 미리 길이가 2보다 작은 경우는 true로 반환(Palindrome 조건에 맞음) + if (s.length < 2) return true; + const formatted: string[] = []; + + // 문자열을 순회하면서 조건에 맞는 문자만 소문자로 변환해서 배열에 저장 + for (let c of s) { + if ( + (c >= "a" && c <= "z") || + (c >= "A" && c <= "Z") || + (c >= "0" && c <= "9") + ) + formatted.push(c.toLowerCase()); + } + // formatted 배열을 reverse하여 JSON.stringify로 비교 (중요) + // ? toReverse()가 chrome console에서는 작동하는데 여기서는 왜 안되는지 모르겠음 + const reversed = [...formatted].reverse(); + return JSON.stringify(reversed) === JSON.stringify(formatted); +} From 30a1246f73562ee7570b6490857cbf811836aec9 Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 14:11:15 +0900 Subject: [PATCH 104/396] 128. Longest Consecutive Sequence --- longest-consecutive-sequence/y00eunji.js | 27 ++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 longest-consecutive-sequence/y00eunji.js diff --git a/longest-consecutive-sequence/y00eunji.js b/longest-consecutive-sequence/y00eunji.js new file mode 100644 index 000000000..56984c5e8 --- /dev/null +++ b/longest-consecutive-sequence/y00eunji.js @@ -0,0 +1,27 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function(nums) { + const numSet = new Set(nums); + let longestStreak = 0; + + for (const num of numSet) { + // 현재 숫자가 연속 시퀀스의 시작점인지 확인 + // 즉, num-1이 set에 없어야 함 + if (!numSet.has(num - 1)) { + let currentNum = num; + let currentStreak = 1; + + // 현재 숫자의 연속된 다음 숫자들을 찾음 + while (numSet.has(currentNum + 1)) { + currentNum += 1; + currentStreak += 1; + } + + longestStreak = Math.max(longestStreak, currentStreak); + } + } + + return longestStreak; +}; From d9a598815d9c3d8c4df854307edc01a2009bd648 Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 14:26:37 +0900 Subject: [PATCH 105/396] 347. Top K Frequent Elements --- top-k-frequent-elements/y00eunji.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/top-k-frequent-elements/y00eunji.js b/top-k-frequent-elements/y00eunji.js index 9e634ee86..bb8b37301 100644 --- a/top-k-frequent-elements/y00eunji.js +++ b/top-k-frequent-elements/y00eunji.js @@ -5,9 +5,9 @@ */ var topKFrequent = function(nums, k) { // 1. nums 배열을 순회하여 각 숫자의 빈도를 계산하고 obj 객체에 저장 - const obj = nums.reduce((arr, idx) => { - arr[idx] = (arr[idx] || 0) + 1; - return arr; + const obj = nums.reduce((acc, cur) => { + acc[cur] = (acc[cur] || 0) + 1; + return acc; }, {}); // 2. obj 객체의 키-값 쌍을 배열로 변환하고, 값을 기준으로 내림차순 정렬, k개 추출 From 5d2718a40f6ddf3f1bef1c45149f4acc3ad1684c Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 14:40:20 +0900 Subject: [PATCH 106/396] 198. House Robber --- house-robber/y00eunji.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 house-robber/y00eunji.js diff --git a/house-robber/y00eunji.js b/house-robber/y00eunji.js new file mode 100644 index 000000000..68a041856 --- /dev/null +++ b/house-robber/y00eunji.js @@ -0,0 +1,26 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + const len = nums.length; + if (len === 0) return 0; + if (len === 1) return nums[0]; + if (len === 2) return Math.max(nums[0], nums[1]); + + const dp = Array(len).fill(0); + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + + // 현재 집을 터는 경우와 안 터는 경우 중 최대값 선택 + // 1. 이전 집까지의 최대 금액 (현재 집 스킵) + // 2. 전전 집까지의 최대 금액 + 현재 집 금액 (현재 집 선택) + for (let i = 2; i < len; i++) { + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); + } + + return dp[len - 1]; +}; + +console.log(rob([1,2,3,1])); // 4 +console.log(rob([2,7,9,3,1])); // 12 \ No newline at end of file From 23502e002842029d441a9a9ae0e3256ef53a46b7 Mon Sep 17 00:00:00 2001 From: y00eunji Date: Mon, 9 Dec 2024 14:40:31 +0900 Subject: [PATCH 107/396] 198. House Robber --- house-robber/y00eunji.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/house-robber/y00eunji.js b/house-robber/y00eunji.js index 68a041856..f9d75694c 100644 --- a/house-robber/y00eunji.js +++ b/house-robber/y00eunji.js @@ -21,6 +21,3 @@ var rob = function(nums) { return dp[len - 1]; }; - -console.log(rob([1,2,3,1])); // 4 -console.log(rob([2,7,9,3,1])); // 12 \ No newline at end of file From 4fbabfc8d11b3f355f3e3fbd6056490297724603 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Mon, 9 Dec 2024 14:45:53 +0900 Subject: [PATCH 108/396] =?UTF-8?q?PR=20Comment=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- top-k-frequent-elements/EcoFriendlyAppleSu.kt | 5 ++++- valid-palindrome/EcoFriendlyAppleSu.kt | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/top-k-frequent-elements/EcoFriendlyAppleSu.kt b/top-k-frequent-elements/EcoFriendlyAppleSu.kt index e171f6131..952ff3318 100644 --- a/top-k-frequent-elements/EcoFriendlyAppleSu.kt +++ b/top-k-frequent-elements/EcoFriendlyAppleSu.kt @@ -3,7 +3,10 @@ package leetcode_study /** * 주어진 숫자들에서 빈도 수가 가장 큰 k 개의 숫자를 구하는 문제. map 자료구조를 사용해 해결 * 시간 복잡도 : O(n) - * -> Int Array를 순회해 map에 담는 과정 + * -> Int Array를 순회해 map에 담는 과정 O(n) + * -> 채워진 Map 자료구조에서 value 기준 내림차순으로 정렬 과정 O(nlogn) + * -> 정렬된 Map에서 K 만큼 값을 가져오는 과정 O(K). (k는 상수) + * 각 단계의 시간 복잡도를 더하면 : O(n) + O(nlogn) + O(k) -> O(nlogn) * 공간 복잡도 : O(n) * -> Int Array에 존재하는 유니크한 요소 만큼 필요함. */ diff --git a/valid-palindrome/EcoFriendlyAppleSu.kt b/valid-palindrome/EcoFriendlyAppleSu.kt index f7beadc2e..cc13be75f 100644 --- a/valid-palindrome/EcoFriendlyAppleSu.kt +++ b/valid-palindrome/EcoFriendlyAppleSu.kt @@ -9,7 +9,7 @@ fun isPalindrome(s: String): Boolean { // 주어진 문자열에서 모든 non-alphanumeric characters를 필터한 문자 배열 할당 val splitGivenString = s.toCharArray() - .filter { it.isLetter() || it.isDigit() } + .filter { it.isLetterOrDigit() } .map { it.lowercaseChar() } .toCharArray() From f7bf00a1e029a98d76277629835c552624bb8631 Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Mon, 9 Dec 2024 16:03:54 +0900 Subject: [PATCH 109/396] feat: Top K Frequent Elements #237 --- top-k-frequent-elements/donghyeon95.java | 29 ++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 top-k-frequent-elements/donghyeon95.java diff --git a/top-k-frequent-elements/donghyeon95.java b/top-k-frequent-elements/donghyeon95.java new file mode 100644 index 000000000..92f8a2b69 --- /dev/null +++ b/top-k-frequent-elements/donghyeon95.java @@ -0,0 +1,29 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +class Solution { + public int[] topKFrequent(int[] nums, int k) { + HashMap hm = new HashMap<>(); + + for (int num: nums) { + hm.put(num, hm.getOrDefault(num, 0)+1); + } + + List> list = new ArrayList<>(hm.entrySet()); + list.sort(Map.Entry.comparingByValue(Collections.reverseOrder())); + + int index = 1; + ArrayList answer = new ArrayList<>(); + for (Map.Entry entry: list) { + if (index > k) break; + answer.add(entry.getKey()); + index++; + } + + return answer.stream().mapToInt(Integer::intValue).toArray(); + } +} + From 4ac448166979058f824a4152fa14b63bc28f13b0 Mon Sep 17 00:00:00 2001 From: kdh-92 Date: Mon, 9 Dec 2024 18:54:54 +0900 Subject: [PATCH 110/396] =?UTF-8?q?Check=20filename=20rules=20=ED=95=B4?= =?UTF-8?q?=EA=B2=B0=20=EC=8B=9C=EB=8F=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- longest-consecutive-sequence/kdh-92.java | 6 +-- top-k-frequent-elements/kdh-92.java | 56 ++++++++++++------------ 2 files changed, 31 insertions(+), 31 deletions(-) diff --git a/longest-consecutive-sequence/kdh-92.java b/longest-consecutive-sequence/kdh-92.java index 7b548d43a..f9fb62cbc 100644 --- a/longest-consecutive-sequence/kdh-92.java +++ b/longest-consecutive-sequence/kdh-92.java @@ -39,7 +39,7 @@ public int longestConsecutive(int[] nums) { } for(int key : hm.keySet()){ - if(hm.containsKey(key - 1)== false){ + if(hm.containsKey(key - 1)){ hm.put(key, true); } } @@ -47,8 +47,8 @@ public int longestConsecutive(int[] nums) { int max = 0; for(int key : hm.keySet()){ int k =1; - if(hm.get(key) == true){ - while(hm.containsKey(key + k) == true){ + if(hm.get(key)){ + while(hm.containsKey(key + k)){ k++; } } diff --git a/top-k-frequent-elements/kdh-92.java b/top-k-frequent-elements/kdh-92.java index 3759619e9..745fab795 100644 --- a/top-k-frequent-elements/kdh-92.java +++ b/top-k-frequent-elements/kdh-92.java @@ -43,40 +43,40 @@ public int[] topKFrequent(int[] nums, int k) { // 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(); + 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 frequencyMap = new HashMap<>(); - for (int num : nums) { - frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); - } + Map frequencyMap = new HashMap<>(); + for (int num : nums) { + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); + } - List[] 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[] 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 result = new ArrayList<>(); - for (int i = buckets.length - 1; i >= 0 && result.size() < k; i--) { - if (buckets[i] != null) { - result.addAll(buckets[i]); - } - } + List 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(); + return result.stream().mapToInt(Integer::intValue).toArray(); } -} +} \ No newline at end of file From 7555cad78527c692f8d5dd4ef576ce647598638a Mon Sep 17 00:00:00 2001 From: thispath98 Date: Mon, 9 Dec 2024 21:32:02 +0900 Subject: [PATCH 111/396] Contains Duplicate --- contains-duplicate/thispath98.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 contains-duplicate/thispath98.py diff --git a/contains-duplicate/thispath98.py b/contains-duplicate/thispath98.py new file mode 100644 index 000000000..21c471339 --- /dev/null +++ b/contains-duplicate/thispath98.py @@ -0,0 +1,15 @@ +""" +# Time Complexity: O(N) +- N번 순회 +# Space Compelexity: O(N) +- 최악의 경우 (중복된 값이 없을 경우) N개 저장 +""" +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + num_dict = {} + for num in nums: + if num not in num_dict: + num_dict[num] = True + else: + return True + return False From dc36e33efbbd8145477f7b87381823ba38c610b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=81=EC=9E=AC?= Date: Mon, 9 Dec 2024 21:37:32 +0900 Subject: [PATCH 112/396] add: solve #237 Top K Frequent Elements with ts --- top-k-frequent-elements/YJason-K.ts | 34 +++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 top-k-frequent-elements/YJason-K.ts diff --git a/top-k-frequent-elements/YJason-K.ts b/top-k-frequent-elements/YJason-K.ts new file mode 100644 index 000000000..b406499e2 --- /dev/null +++ b/top-k-frequent-elements/YJason-K.ts @@ -0,0 +1,34 @@ +/** + * 배열에서 각 숫자의 빈도를 계산한 후 상위 k개의 빈도 요소를 반환하는 함수 + * - 시간 복잡도: O(n + m log m) + * - O(n): 숫자 빈도를 계산하는 루프 + * - O(m log m): 고유 숫자(m)에 대한 정렬 + * - 공간 복잡도: O(m) + * - 고유 숫자(m)에 비례한 Map과 정렬된 배열 사용 + * + * @param {number[]} nums - 숫자 배열 + * @param {number} k - 반환할 상위 빈도 요소의 개수 + * @returns {number[]} 상위 k개의 빈도 요소 (순서는 상관 없음) + */ +function topKFrequent(nums: number[], k: number): number[] { + let numMap = new Map(); // 숫자의 빈도를 저장할 Map + + // 1. 숫자 빈도 Map 생성 O(n) + for (const num of nums) { + // Map에 현재 숫자가 없으면 1로 초기화, 있으면 1 증가 + const value = numMap.get(num) ? numMap.get(num) + 1 : 1; + numMap.set(num, value); + } + + // 2. Map을 [숫자, 빈도수] 배열로 변환한 뒤 빈도수 기준 내림차순 정렬 O(m log m) + const sortedFrequent = [...numMap.entries()] // Map을 배열로 변환 + .sort((a, b) => b[1] - a[1]) // 빈도수 기준 내림차순 정렬 + + // 3. 상위 k개의 숫자만 추출 O(k) + .slice(0, k) + + // 4. 숫자(key)만 추출 O(k) + .map(entry => entry[0]); + + return sortedFrequent; +} From 8918c97b1fd1c593830e40ae82dbeb86e6a88644 Mon Sep 17 00:00:00 2001 From: thispath98 Date: Mon, 9 Dec 2024 21:50:53 +0900 Subject: [PATCH 113/396] Valid Palindrome --- valid-palindrome/thispath98.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 valid-palindrome/thispath98.py diff --git a/valid-palindrome/thispath98.py b/valid-palindrome/thispath98.py new file mode 100644 index 000000000..142bc1a13 --- /dev/null +++ b/valid-palindrome/thispath98.py @@ -0,0 +1,13 @@ +""" +# Time Complexity: O(N) +- N개의 char를 각각 한번씩 순회 +# Space Compelexity: O(N) +- 최악의 경우 (공백이 없을 경우) N개의 char 저장 +""" +class Solution: + def isPalindrome(self, s: str) -> bool: + string = [char.lower() for char in s if char.isalnum()] + for i in range(len(string) // 2): + if string[i] != string[-i - 1]: + return False + return True From 6ae4bbe4fc4af4c38259c9cf022e6f6fe8f6f38e Mon Sep 17 00:00:00 2001 From: Minji Ko Date: Mon, 9 Dec 2024 22:00:06 +0900 Subject: [PATCH 114/396] feat: top k frequent elements --- top-k-frequent-elements/minji-go.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 top-k-frequent-elements/minji-go.java diff --git a/top-k-frequent-elements/minji-go.java b/top-k-frequent-elements/minji-go.java new file mode 100644 index 000000000..9d2e8bc8a --- /dev/null +++ b/top-k-frequent-elements/minji-go.java @@ -0,0 +1,18 @@ +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map count = new HashMap<>(); + for(int num : nums){ + count.put(num, count.getOrDefault(num, 0)+1); + } + List tops = count.keySet().stream() + .sorted((i1, i2) -> count.get(i2)-count.get(i1)) + .limit(k) + .toList(); + + int[] answer = new int[k]; + for(int i=0; i Date: Mon, 9 Dec 2024 22:03:54 +0900 Subject: [PATCH 115/396] feat: longest consecutive sequence --- longest-consecutive-sequence/minji-go.java | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 longest-consecutive-sequence/minji-go.java diff --git a/longest-consecutive-sequence/minji-go.java b/longest-consecutive-sequence/minji-go.java new file mode 100644 index 000000000..04e94c1ea --- /dev/null +++ b/longest-consecutive-sequence/minji-go.java @@ -0,0 +1,22 @@ +class Solution { + public int longestConsecutive(int[] nums) { + Set set = new HashSet<>(); + for(int num: nums) { + set.add(num); + } + + int answer = 0; + for(int num: nums){ + if(set.contains(num-1)){ + continue; + } + int length = 1; + while (set.contains(num+length)){ + length++; + } + answer = Math.max(answer, length); + } + + return answer; + } +} From e07436ca93e5c1d6867165465c10a5f87f14cf26 Mon Sep 17 00:00:00 2001 From: thispath98 Date: Mon, 9 Dec 2024 22:08:25 +0900 Subject: [PATCH 116/396] Top K Frequent Elements --- top-k-frequent-elements/thispath98.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 top-k-frequent-elements/thispath98.py diff --git a/top-k-frequent-elements/thispath98.py b/top-k-frequent-elements/thispath98.py new file mode 100644 index 000000000..3c21195a0 --- /dev/null +++ b/top-k-frequent-elements/thispath98.py @@ -0,0 +1,16 @@ +""" +# Time Complexity: O(N log N) +- Counter 생성: N번 순회 +- most common 연산: N log N +# Space Compelexity: O(N) +- 최악의 경우 (중복된 값이 없을 경우) N개 저장 +""" +from collections import Counter + + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count_dict = Counter(nums) + top_k_list = count_dict.most_common(k) + answer = [key for key, value in top_k_list] + return answer From ec729e10c7d6a7217047794b33b7243202069010 Mon Sep 17 00:00:00 2001 From: Minji Ko Date: Mon, 9 Dec 2024 22:08:36 +0900 Subject: [PATCH 117/396] feat: house robber --- house-robber/minji-go.java | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 house-robber/minji-go.java diff --git a/house-robber/minji-go.java b/house-robber/minji-go.java new file mode 100644 index 000000000..3aa8bdcc6 --- /dev/null +++ b/house-robber/minji-go.java @@ -0,0 +1,11 @@ +class Solution { + public int rob(int[] nums) { + int[] sum = new int[nums.length+1]; + sum[0] = nums[0]; + if(nums.length>1) sum[1] = Math.max(nums[0], nums[1]); + for(int i=2; i Date: Mon, 9 Dec 2024 22:41:02 +0900 Subject: [PATCH 118/396] Longest Consecutive Sequence --- longest-common-subsequence/thispath98.py | 37 ++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 longest-common-subsequence/thispath98.py diff --git a/longest-common-subsequence/thispath98.py b/longest-common-subsequence/thispath98.py new file mode 100644 index 000000000..5a9a1e457 --- /dev/null +++ b/longest-common-subsequence/thispath98.py @@ -0,0 +1,37 @@ +""" +# Time Complexity: O(N) +- lce_dict 생성: N +- N개의 key에 대하여 순회하면서 값 확인: N +# Space Compelexity: O(k) +- 중복되지 않은 key k개 저장 +""" +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + if not nums: + return 0 + + lce_dict = {} + for num in nums: + lce_dict[num] = True + + answer = 0 + for num in nums: + cur_lce = 1 + if lce_dict.pop(num, None) is None: + continue + + down_num = num - 1 + while down_num in lce_dict: + cur_lce += 1 + lce_dict.pop(down_num) + down_num -= 1 + + up_num = num + 1 + while up_num in lce_dict: + cur_lce += 1 + lce_dict.pop(up_num) + up_num += 1 + + answer = answer if answer > cur_lce else cur_lce + + return answer From 2fd0eef5d7749a07641ef3252aae0c11fcf39940 Mon Sep 17 00:00:00 2001 From: thispath98 Date: Mon, 9 Dec 2024 23:00:27 +0900 Subject: [PATCH 119/396] House Robber --- house-robber/thispath98.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 house-robber/thispath98.py diff --git a/house-robber/thispath98.py b/house-robber/thispath98.py new file mode 100644 index 000000000..befc6f2ba --- /dev/null +++ b/house-robber/thispath98.py @@ -0,0 +1,19 @@ +""" +# Time Complexity: O(N) +- N개의 개수를 가지는 dp 리스트를 만들고, 이를 순회 +# Space Compelexity: O(N) +- N개의 dp 리스트 저장 +""" +class Solution: + def rob(self, nums: List[int]) -> int: + if len(nums) == 1: + return nums[0] + + dp = [0 for _ in range(len(nums))] + dp[0] = nums[0] + dp[1] = max(nums[0], nums[1]) + + for i in range(len(nums) - 2): + dp[i + 2] = max(dp[i] + nums[i + 2], dp[i + 1]) + + return max(dp[-2], dp[-1]) From 5aaca9941cb94537890f25ff288a393dee394480 Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Mon, 9 Dec 2024 23:21:31 +0900 Subject: [PATCH 120/396] [week1] contains-duplicate - hjtag.kt --- contains-duplicate/hjtag.kt | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 contains-duplicate/hjtag.kt diff --git a/contains-duplicate/hjtag.kt b/contains-duplicate/hjtag.kt new file mode 100644 index 000000000..ec2edd0f5 --- /dev/null +++ b/contains-duplicate/hjtag.kt @@ -0,0 +1,7 @@ +package leetcode_study + +class Solution { + fun containsDuplicate(nums: IntArray): Boolean { + return nums.toSet().size != nums.size + } +} From 2e0a8fe3a62713a33c0725883ce770cbe7bcad04 Mon Sep 17 00:00:00 2001 From: jeehay Date: Mon, 9 Dec 2024 23:34:32 +0900 Subject: [PATCH 121/396] longest-consecutive-sequence solution --- longest-consecutive-sequence/Jeehay28.js | 31 ++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 longest-consecutive-sequence/Jeehay28.js diff --git a/longest-consecutive-sequence/Jeehay28.js b/longest-consecutive-sequence/Jeehay28.js new file mode 100644 index 000000000..f1f92ecf4 --- /dev/null +++ b/longest-consecutive-sequence/Jeehay28.js @@ -0,0 +1,31 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + let result = []; + let longest = []; + + numsSorted = nums.sort((a, b) => a - b); + + numsFiltered = [...new Set(numsSorted)]; + + for (let i = 0; i < numsFiltered.length; i++) { + if (result.length === 0) { + result.push(numsFiltered[i]); + } else if (result.length >= 1) { + if (numsFiltered[i] === result[result.length - 1] + 1) { + result.push(numsFiltered[i]); + } else { + longest.push(result.length); + result = [numsFiltered[i]]; + } + } + } + + if (longest.length === 0) { + return result.length; + } else { + return Math.max(Math.max(...longest), result.length); + } +}; From 1101bc145940719a1194c742bd623171579678ee Mon Sep 17 00:00:00 2001 From: csucom Date: Sun, 24 Nov 2024 22:40:24 +0900 Subject: [PATCH 122/396] add sample code for testing --- 3sum/csucom.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 3sum/csucom.py diff --git a/3sum/csucom.py b/3sum/csucom.py new file mode 100644 index 000000000..9def7cf98 --- /dev/null +++ b/3sum/csucom.py @@ -0,0 +1,3 @@ +''' + test code +''' \ No newline at end of file From 2bb46c531736a8d5a275520331450a4583aae9d2 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:10:51 +0900 Subject: [PATCH 123/396] contains-duplicate --- contains-duplicate/jejufather.cpp | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 contains-duplicate/jejufather.cpp diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp new file mode 100644 index 000000000..2b2418ea6 --- /dev/null +++ b/contains-duplicate/jejufather.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +bool containsDuplicate(int* nums, int numsSize) { + char* pflag = (char*)malloc(1000000001); + char* mflag = (char*)malloc(1000000001); + memset(pflag, 0, 1000000001); + memset(mflag, 0, 1000000001); + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < 0) { + if (mflag[-nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + mflag[-nums[i]] = 1; + } + else { + if (pflag[nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + pflag[nums[i]] = 1; + } + } + free(pflag); + free(mflag); + return false; +} + +void main(void) { + int test[100001] = {0}; + printf("%d\n", containsDuplicate(test, 1)); +} \ No newline at end of file From 07dc83002a66010740c51c4853e11bfb6c357956 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:29:27 +0900 Subject: [PATCH 124/396] contains-duplicate --- contains-duplicate/jejufather.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp index 2b2418ea6..81221d523 100644 --- a/contains-duplicate/jejufather.cpp +++ b/contains-duplicate/jejufather.cpp @@ -30,6 +30,7 @@ bool containsDuplicate(int* nums, int numsSize) { return false; } + void main(void) { int test[100001] = {0}; printf("%d\n", containsDuplicate(test, 1)); From 1da888d052773e8bb11ed5420758c5e471d3d5e3 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:36:08 +0900 Subject: [PATCH 125/396] contains-duplicate --- contains-duplicate/jejufather.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp index 81221d523..61544a620 100644 --- a/contains-duplicate/jejufather.cpp +++ b/contains-duplicate/jejufather.cpp @@ -30,8 +30,7 @@ bool containsDuplicate(int* nums, int numsSize) { return false; } - void main(void) { int test[100001] = {0}; printf("%d\n", containsDuplicate(test, 1)); -} \ No newline at end of file +} From 84c2e41016cdacf7d45c32603d217192e9703937 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:31:46 +0900 Subject: [PATCH 126/396] Delete 3sum/csucom.py --- 3sum/csucom.py | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 3sum/csucom.py diff --git a/3sum/csucom.py b/3sum/csucom.py deleted file mode 100644 index 9def7cf98..000000000 --- a/3sum/csucom.py +++ /dev/null @@ -1,3 +0,0 @@ -''' - test code -''' \ No newline at end of file From 2750e33526873143b8535c5fdeb53f19cc684adf Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 00:48:05 +0900 Subject: [PATCH 127/396] contains-duplicate --- contains-duplicate/csucom.cpp | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 contains-duplicate/csucom.cpp diff --git a/contains-duplicate/csucom.cpp b/contains-duplicate/csucom.cpp new file mode 100644 index 000000000..61544a620 --- /dev/null +++ b/contains-duplicate/csucom.cpp @@ -0,0 +1,36 @@ +#include +#include +#include + +bool containsDuplicate(int* nums, int numsSize) { + char* pflag = (char*)malloc(1000000001); + char* mflag = (char*)malloc(1000000001); + memset(pflag, 0, 1000000001); + memset(mflag, 0, 1000000001); + for (int i = 0; i < numsSize; ++i) { + if (nums[i] < 0) { + if (mflag[-nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + mflag[-nums[i]] = 1; + } + else { + if (pflag[nums[i]] == 1) { + free(pflag); + free(mflag); + return true; + } + pflag[nums[i]] = 1; + } + } + free(pflag); + free(mflag); + return false; +} + +void main(void) { + int test[100001] = {0}; + printf("%d\n", containsDuplicate(test, 1)); +} From 9e53feefd265d5a424b50cb09c27a9d619c06356 Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 23:22:49 +0900 Subject: [PATCH 128/396] delete wrong file --- contains-duplicate/jejufather.cpp | 36 ------------------------------- 1 file changed, 36 deletions(-) delete mode 100644 contains-duplicate/jejufather.cpp diff --git a/contains-duplicate/jejufather.cpp b/contains-duplicate/jejufather.cpp deleted file mode 100644 index 61544a620..000000000 --- a/contains-duplicate/jejufather.cpp +++ /dev/null @@ -1,36 +0,0 @@ -#include -#include -#include - -bool containsDuplicate(int* nums, int numsSize) { - char* pflag = (char*)malloc(1000000001); - char* mflag = (char*)malloc(1000000001); - memset(pflag, 0, 1000000001); - memset(mflag, 0, 1000000001); - for (int i = 0; i < numsSize; ++i) { - if (nums[i] < 0) { - if (mflag[-nums[i]] == 1) { - free(pflag); - free(mflag); - return true; - } - mflag[-nums[i]] = 1; - } - else { - if (pflag[nums[i]] == 1) { - free(pflag); - free(mflag); - return true; - } - pflag[nums[i]] = 1; - } - } - free(pflag); - free(mflag); - return false; -} - -void main(void) { - int test[100001] = {0}; - printf("%d\n", containsDuplicate(test, 1)); -} From b213d93ce31a9c7e07b897d15008330c17a5646c Mon Sep 17 00:00:00 2001 From: csucom Date: Mon, 9 Dec 2024 09:55:01 +0900 Subject: [PATCH 129/396] contains-duplicate solution --- contains-duplicate/csucom.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contains-duplicate/csucom.cpp b/contains-duplicate/csucom.cpp index 61544a620..1fcb4171e 100644 --- a/contains-duplicate/csucom.cpp +++ b/contains-duplicate/csucom.cpp @@ -1,4 +1,4 @@ -#include +//#include #include #include @@ -30,7 +30,7 @@ bool containsDuplicate(int* nums, int numsSize) { return false; } -void main(void) { - int test[100001] = {0}; - printf("%d\n", containsDuplicate(test, 1)); -} +// void main(void) { +// int test[100001] = {0}; +// printf("%d\n", containsDuplicate(test, 1)); +// } From 49876ae2bb059a7241fc95430c5428c30bbeeb3f Mon Sep 17 00:00:00 2001 From: Sungwook Choi Date: Mon, 9 Dec 2024 23:43:55 +0900 Subject: [PATCH 130/396] contains-duplicate solution --- contains-duplicate/csucom.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/contains-duplicate/csucom.cpp b/contains-duplicate/csucom.cpp index 1fcb4171e..18057c2f1 100644 --- a/contains-duplicate/csucom.cpp +++ b/contains-duplicate/csucom.cpp @@ -1,4 +1,3 @@ -//#include #include #include @@ -30,7 +29,4 @@ bool containsDuplicate(int* nums, int numsSize) { return false; } -// void main(void) { -// int test[100001] = {0}; -// printf("%d\n", containsDuplicate(test, 1)); -// } + From b37f8ee14a42025decda8d47032c8607860ec7a5 Mon Sep 17 00:00:00 2001 From: Real-Reason Date: Tue, 10 Dec 2024 00:13:50 +0900 Subject: [PATCH 131/396] feat: valid-palindrome solve --- contains-duplicate/Real-Reason.kt | 4 ++-- valid-palindrome/Real-Reason.kt | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 valid-palindrome/Real-Reason.kt diff --git a/contains-duplicate/Real-Reason.kt b/contains-duplicate/Real-Reason.kt index 599bfaa90..c745379d3 100644 --- a/contains-duplicate/Real-Reason.kt +++ b/contains-duplicate/Real-Reason.kt @@ -1,10 +1,10 @@ package leetcode_study -class Solution { +class SolutionContainsDuplicate { fun containsDuplicate(nums: IntArray): Boolean { val size = nums.size val numsToSet = nums.toSet() return size != numsToSet.size } -} \ No newline at end of file +} diff --git a/valid-palindrome/Real-Reason.kt b/valid-palindrome/Real-Reason.kt new file mode 100644 index 000000000..23ae90f07 --- /dev/null +++ b/valid-palindrome/Real-Reason.kt @@ -0,0 +1,27 @@ +package leetcode_study + +class SolutionValidPalindrome { + fun isPalindrome(s: String): Boolean { + val sToCharArray = s.toCharArray() + var startIndex = 0 + var endIndex = sToCharArray.size - 1 + while (startIndex < endIndex) { + if (!sToCharArray[startIndex].isLetterOrDigit() || sToCharArray[startIndex].isWhitespace()) { + startIndex++ + continue + } + if (!sToCharArray[endIndex].isLetterOrDigit() || sToCharArray[endIndex].isWhitespace()) { + endIndex-- + continue + } + if (sToCharArray[startIndex].lowercase() == sToCharArray[endIndex].lowercase()) { + startIndex++ + endIndex-- + } else { + return false + } + } + + return true + } +} From f5c94ae374eec3534b1d8a26cb54470b277a47d4 Mon Sep 17 00:00:00 2001 From: sungjinwi <0202wsj@gmail.com> Date: Tue, 10 Dec 2024 00:25:11 +0900 Subject: [PATCH 132/396] containsDuplicate solution --- contains-duplicate/sungjinwi.c | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 contains-duplicate/sungjinwi.c diff --git a/contains-duplicate/sungjinwi.c b/contains-duplicate/sungjinwi.c new file mode 100644 index 000000000..a70794434 --- /dev/null +++ b/contains-duplicate/sungjinwi.c @@ -0,0 +1,21 @@ +#include +#include + +int compare(void const *a, void const *b) +{ + return (*(int *)a - *(int *)b); +} + +bool containsDuplicate(int* nums, int numsSize) {\ + int i; + + i = 0; + qsort(nums, numsSize, sizeof(int), compare); + while (i < numsSize - 1) + { + if (nums[i] == nums[i + 1]) + return (1); + i++; + } + return (0); +} From 4b99ac73029188d010910753ea56d1c08511e322 Mon Sep 17 00:00:00 2001 From: sungjinwi <0202wsj@gmail.com> Date: Tue, 10 Dec 2024 00:34:35 +0900 Subject: [PATCH 133/396] Docs : complexity calc for containDuplicate --- contains-duplicate/sungjinwi.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/contains-duplicate/sungjinwi.c b/contains-duplicate/sungjinwi.c index a70794434..25adea1b4 100644 --- a/contains-duplicate/sungjinwi.c +++ b/contains-duplicate/sungjinwi.c @@ -6,7 +6,7 @@ int compare(void const *a, void const *b) return (*(int *)a - *(int *)b); } -bool containsDuplicate(int* nums, int numsSize) {\ +bool containsDuplicate(int* nums, int numsSize) { int i; i = 0; @@ -19,3 +19,19 @@ bool containsDuplicate(int* nums, int numsSize) {\ } return (0); } + +/* + 시간 복잡도 + + qsort(퀵소트)를 통해 O(n log n)을 한 번 수행 + while문을 한 번 돌아서 O(n)만큼의 복잡도를 가짐 + + 최종 시간 복잡도 : O(n log n) + + ============================ + + 공간 복잡도 + + 추가적으로 할당하는 메모리가 없으므로 O(1)의 복잡도를 가진다 + + 최종 공간 복잡도 : O(1) +*/ From 324485eb232a6d4a7d15353263ce00884f3d0d76 Mon Sep 17 00:00:00 2001 From: kdh-92 Date: Tue, 10 Dec 2024 02:52:18 +0900 Subject: [PATCH 134/396] solve : #264 (House Robber) with Java --- house-robber/kdh-92.java | 29 +++++++++++++++++++++++++++++ top-k-frequent-elements/kdh-92.java | 2 +- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 house-robber/kdh-92.java diff --git a/house-robber/kdh-92.java b/house-robber/kdh-92.java new file mode 100644 index 000000000..a98ff6092 --- /dev/null +++ b/house-robber/kdh-92.java @@ -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; + } +} diff --git a/top-k-frequent-elements/kdh-92.java b/top-k-frequent-elements/kdh-92.java index 745fab795..17e74ab56 100644 --- a/top-k-frequent-elements/kdh-92.java +++ b/top-k-frequent-elements/kdh-92.java @@ -79,4 +79,4 @@ public int[] topKFrequent(int[] nums, int k) { return result.stream().mapToInt(Integer::intValue).toArray(); } -} \ No newline at end of file +} From b89edeefd63cabae2a86b4988e99534aea319c76 Mon Sep 17 00:00:00 2001 From: siroo Date: Tue, 10 Dec 2024 04:42:18 +0900 Subject: [PATCH 135/396] contains duplicate solution --- contains-duplicate/jungsiroo.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 contains-duplicate/jungsiroo.py diff --git a/contains-duplicate/jungsiroo.py b/contains-duplicate/jungsiroo.py new file mode 100644 index 000000000..9ff59bc86 --- /dev/null +++ b/contains-duplicate/jungsiroo.py @@ -0,0 +1,18 @@ +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + # Slow - tc : O(n) / sc : O(1) + + """return len(set(nums)) != len(nums)""" + + # Fast - tc : O(n) / sc : O(n) + check = set() + + for num in nums: + if num in check: + return True + check.add(num) + + return False + + + From 0c219856441285f5bc989cdb9a009ca21000e33a Mon Sep 17 00:00:00 2001 From: siroo Date: Tue, 10 Dec 2024 04:53:21 +0900 Subject: [PATCH 136/396] valid palindrome solution --- valid-palindrome/jungsiroo.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 valid-palindrome/jungsiroo.py diff --git a/valid-palindrome/jungsiroo.py b/valid-palindrome/jungsiroo.py new file mode 100644 index 000000000..87dfa11f9 --- /dev/null +++ b/valid-palindrome/jungsiroo.py @@ -0,0 +1,7 @@ +import re + +class Solution: + def isPalindrome(self, s: str) -> bool: + # Fastest - tc : O(n) / sc : O(1 + s = ''.join(re.findall(r'[a-z0-9]+', s.lower())) + return s == ''.join(reversed(s)) From e372a24c1e6b3e7259b6f46b19ec363d4f8f479e Mon Sep 17 00:00:00 2001 From: siroo Date: Tue, 10 Dec 2024 05:24:19 +0900 Subject: [PATCH 137/396] Top K Frequent Elements solution --- top-k-frequent-elements/jungsiroo.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 top-k-frequent-elements/jungsiroo.py diff --git a/top-k-frequent-elements/jungsiroo.py b/top-k-frequent-elements/jungsiroo.py new file mode 100644 index 000000000..a60e117b1 --- /dev/null +++ b/top-k-frequent-elements/jungsiroo.py @@ -0,0 +1,26 @@ +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + # Naive Solution + # TC : O(nlogn) + # SC : O(n) + + cnt = dict() + for num in nums: + cnt[num] = cnt.get(num, 0) + 1 + + """ + ret = dict(sorted(cnt.items(), key=lambda x:(-x[1], x[0]))) + return list(ret.keys())[:k] + """ + + # Follow up Solution + # TC : O(nlog(k)) + # SC : O(n) + + import heapq + + ret = [(-c, num) for num, c in cnt.items()] + heapq.heapify(ret) + + return [heapq.heappop(ret)[1] for _ in range(k)] + From 1a00ff9e4e33d297cda7e7fdc2e9d79f56f70ea8 Mon Sep 17 00:00:00 2001 From: easyone Date: Tue, 10 Dec 2024 07:32:29 +0900 Subject: [PATCH 138/396] Feat: Add solution of contains-duplicate --- contains-duplicate/easyone-jwlee.go | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 contains-duplicate/easyone-jwlee.go diff --git a/contains-duplicate/easyone-jwlee.go b/contains-duplicate/easyone-jwlee.go new file mode 100644 index 000000000..7d552ba43 --- /dev/null +++ b/contains-duplicate/easyone-jwlee.go @@ -0,0 +1,10 @@ +func containsDuplicate(nums []int) bool { + m := make(map[int]int) + for _, num := range nums { + if _, ok := m[num]; ok { + return true + } + m[num] = num + } + return false +} \ No newline at end of file From 41b208687e4f03e885a18402a1224ad5e464817d Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 10 Dec 2024 07:56:00 +0900 Subject: [PATCH 139/396] docs: add space complexity of Tim-sort --- top-k-frequent-elements/Chaedie.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/top-k-frequent-elements/Chaedie.py b/top-k-frequent-elements/Chaedie.py index 5b6241049..8ecf9775e 100644 --- a/top-k-frequent-elements/Chaedie.py +++ b/top-k-frequent-elements/Chaedie.py @@ -13,7 +13,8 @@ Space Complexity: 1. dictionary for counting frequency of nums -> O(n) - 2. sorted List -> O(n) + 2. Timsort's space overhead -> O(n) + 3. sorted List -> O(n) Space complexity of this solution is O(n) """ From dd26a7e5e6b5e2ddb806a045cfbc3a4e1585ee51 Mon Sep 17 00:00:00 2001 From: ChaedongIm Date: Tue, 10 Dec 2024 07:58:50 +0900 Subject: [PATCH 140/396] docs: add space complexity of string[::-1] --- valid-palindrome/Chaedie.py | 1 + 1 file changed, 1 insertion(+) diff --git a/valid-palindrome/Chaedie.py b/valid-palindrome/Chaedie.py index 9696aa1c5..1a23c5c8b 100644 --- a/valid-palindrome/Chaedie.py +++ b/valid-palindrome/Chaedie.py @@ -14,6 +14,7 @@ 공간 복잡도: 1) string 배열 - O(n) + 2) string[::-1] - O(n) 결론: O(n) 입니다. """ From 11b4bc53b46ddcae2b7aabe6fd948a1b4a563a7a Mon Sep 17 00:00:00 2001 From: Paik Date: Tue, 10 Dec 2024 08:12:22 +0900 Subject: [PATCH 141/396] feat: 347. Top K Frequent Elements --- top-k-frequent-elements/gwbaik9717.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 top-k-frequent-elements/gwbaik9717.js diff --git a/top-k-frequent-elements/gwbaik9717.js b/top-k-frequent-elements/gwbaik9717.js new file mode 100644 index 000000000..a539d1198 --- /dev/null +++ b/top-k-frequent-elements/gwbaik9717.js @@ -0,0 +1,24 @@ +// Time complexity: O(nlogn) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function (nums, k) { + const frequencyDict = new Map(); + + for (const num of nums) { + if (frequencyDict.has(num)) { + frequencyDict.set(num, frequencyDict.get(num) + 1); + } else { + frequencyDict.set(num, 1); + } + } + + const entries = [...frequencyDict.entries()]; + entries.sort((a, b) => b[1] - a[1]); + + return entries.slice(0, k).map((entry) => entry[0]); +}; From 52b09c0541cbc2f1de8a26176ded03cffe92b27a Mon Sep 17 00:00:00 2001 From: easyone Date: Tue, 10 Dec 2024 08:22:19 +0900 Subject: [PATCH 142/396] Feat: Add solution of valid-palindrome --- contains-duplicate/easyone-jwlee.go | 2 +- valid-palindrome/easyone-jwlee.go | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 valid-palindrome/easyone-jwlee.go diff --git a/contains-duplicate/easyone-jwlee.go b/contains-duplicate/easyone-jwlee.go index 7d552ba43..692163447 100644 --- a/contains-duplicate/easyone-jwlee.go +++ b/contains-duplicate/easyone-jwlee.go @@ -7,4 +7,4 @@ func containsDuplicate(nums []int) bool { m[num] = num } return false -} \ No newline at end of file +} diff --git a/valid-palindrome/easyone-jwlee.go b/valid-palindrome/easyone-jwlee.go new file mode 100644 index 000000000..8b344942a --- /dev/null +++ b/valid-palindrome/easyone-jwlee.go @@ -0,0 +1,20 @@ +func isPalindrome(s string) bool { + s = strings.ToLower(s) + validStr := "" + for _, str := range s { + if ('a' > str || 'z' < str) && ('0' > str || '9' < str) { + continue + } + validStr += string(str) + } + if len(validStr) <= 1 { + return true + } + l := len(validStr) + for i := 0; i < l/2; i++ { + if validStr[i] != validStr[l-1-i] { + return false + } + } + return true +} From 02cc9222f6d3c1c08147148a502bd3fd80f0d635 Mon Sep 17 00:00:00 2001 From: HC-kang Date: Tue, 10 Dec 2024 08:23:54 +0900 Subject: [PATCH 143/396] chore: modify PR template and add rust tag label --- .github/labeler.yml | 5 +++++ .github/pull_request_template.md | 10 ++++++---- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/.github/labeler.yml b/.github/labeler.yml index 2e49f80bb..7350d426b 100644 --- a/.github/labeler.yml +++ b/.github/labeler.yml @@ -52,3 +52,8 @@ elixir: - changed-files: - any-glob-to-any-file: - "**/*.exs" + +rust: + - changed-files: + - any-glob-to-any-file: + - "**/*.rs" diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index fb9518185..b465cf5de 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,17 +1,19 @@ ## 답안 제출 문제 - [ ] 문제 1 - [ ] 문제 2 - [ ] 문제 3 + ## 체크 리스트 -- [ ] PR을 프로젝트에 추가하고 Week를 현재 주차로 설정해주세요. +- [ ] 우측 메뉴에서 PR을 **Projects**에 추가해주세요. +- [ ] **Projects**의 오른쪽 버튼(▼)을 눌러 확장한 뒤, **Week**를 현재 주차로 설정해주세요. - [ ] 바로 앞에 PR을 열어주신 분을 코드 검토자로 지정해주세요. -- [ ] 문제를 모두 푸시면 프로젝트에서 Status를 `In Review`로 설정해주세요. +- [ ] 문제를 모두 푸시면 프로젝트에서 **Status**를 `In Review`로 설정해주세요. - [ ] 코드 검토자 1분 이상으로부터 승인을 받으셨다면 PR을 병합해주세요. From 15811f5abc1641826b28109a84773225484129f3 Mon Sep 17 00:00:00 2001 From: easyone Date: Tue, 10 Dec 2024 07:32:29 +0900 Subject: [PATCH 144/396] Feat: Add solution of contains-duplicate --- contains-duplicate/easyone-jwlee.go | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 contains-duplicate/easyone-jwlee.go diff --git a/contains-duplicate/easyone-jwlee.go b/contains-duplicate/easyone-jwlee.go new file mode 100644 index 000000000..7d552ba43 --- /dev/null +++ b/contains-duplicate/easyone-jwlee.go @@ -0,0 +1,10 @@ +func containsDuplicate(nums []int) bool { + m := make(map[int]int) + for _, num := range nums { + if _, ok := m[num]; ok { + return true + } + m[num] = num + } + return false +} \ No newline at end of file From a9dd0c75357b7f0ea2e89bd4527d0dc85dea43d3 Mon Sep 17 00:00:00 2001 From: easyone Date: Tue, 10 Dec 2024 08:22:19 +0900 Subject: [PATCH 145/396] Feat: Add solution of valid-palindrome --- contains-duplicate/easyone-jwlee.go | 2 +- valid-palindrome/easyone-jwlee.go | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 valid-palindrome/easyone-jwlee.go diff --git a/contains-duplicate/easyone-jwlee.go b/contains-duplicate/easyone-jwlee.go index 7d552ba43..692163447 100644 --- a/contains-duplicate/easyone-jwlee.go +++ b/contains-duplicate/easyone-jwlee.go @@ -7,4 +7,4 @@ func containsDuplicate(nums []int) bool { m[num] = num } return false -} \ No newline at end of file +} diff --git a/valid-palindrome/easyone-jwlee.go b/valid-palindrome/easyone-jwlee.go new file mode 100644 index 000000000..8b344942a --- /dev/null +++ b/valid-palindrome/easyone-jwlee.go @@ -0,0 +1,20 @@ +func isPalindrome(s string) bool { + s = strings.ToLower(s) + validStr := "" + for _, str := range s { + if ('a' > str || 'z' < str) && ('0' > str || '9' < str) { + continue + } + validStr += string(str) + } + if len(validStr) <= 1 { + return true + } + l := len(validStr) + for i := 0; i < l/2; i++ { + if validStr[i] != validStr[l-1-i] { + return false + } + } + return true +} From 8887ab84676374ec3ef7d76a4b1ab759310d2ac7 Mon Sep 17 00:00:00 2001 From: gmlwls96 Date: Tue, 10 Dec 2024 11:28:26 +0900 Subject: [PATCH 146/396] =?UTF-8?q?=EC=9D=B4=EB=A6=84=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/{hjtag.kt => gmlwls96.kt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{hjtag.kt => gmlwls96.kt} (100%) diff --git a/contains-duplicate/hjtag.kt b/contains-duplicate/gmlwls96.kt similarity index 100% rename from contains-duplicate/hjtag.kt rename to contains-duplicate/gmlwls96.kt From abc84fcaabce38d6bc398ac7e60b7ef58a3d9367 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Tue, 10 Dec 2024 12:31:33 +0900 Subject: [PATCH 147/396] Add solution for "217. Contains Duplicate" --- contains-duplicate/KwonNayeon.py | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/contains-duplicate/KwonNayeon.py b/contains-duplicate/KwonNayeon.py index e69de29bb..afe1cfc43 100644 --- a/contains-duplicate/KwonNayeon.py +++ b/contains-duplicate/KwonNayeon.py @@ -0,0 +1,39 @@ +""" +Title: 217. Contains Duplicate +Link: https://leetcode.com/problems/contains-duplicate/ + +Summary: + - 주어진 배열 `nums`에서 어떤 값이 한 번 이상 등장하면 True를 반환하고, 배열의 모든 값이 유일한 경우에는 False를 반환함 + - Input: `nums = [1,2,3,1]` + - Output: `True` + +Conditions: + - 중복이 있으면: 배열에서 적어도 하나의 값이 두 번 이상 등장하면 `True` 반환 + - 중복이 없으면: 배열의 모든 값이 유일하면 `False` 반환 +""" + +""" +First Try +Time Complexity: + - O(n) * O(n) = O(n^2): `for` 루프에서 `nums.count(i)`를 호출할 때마다 리스트를 순회하므로, 전체 시간 복잡도는 `O(n^2)` +""" +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + for i in nums: + if nums.count(i) > 1: + return True + return False + +""" +Second Try (set를 활용하여 이미 본 요소를 효율적으로 추적하는 방법) +Time Complexity: + - O(n): `for` 루프에서 각 숫자에 대해 `in` 연산과 `add` 연산이 상수 시간 O(1)으로 처리되므로, 전체 시간 복잡도는 O(n) +""" +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + seen = set() + for i in nums: + if i in seen: + return True + seen.add(i) + return False \ No newline at end of file From c8199c99b9277c45372833da4a4d4b425eca6464 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Tue, 10 Dec 2024 12:52:56 +0900 Subject: [PATCH 148/396] Add newline at the end of the file to comply with the CI requirements --- contains-duplicate/KwonNayeon.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/KwonNayeon.py b/contains-duplicate/KwonNayeon.py index afe1cfc43..090989dab 100644 --- a/contains-duplicate/KwonNayeon.py +++ b/contains-duplicate/KwonNayeon.py @@ -36,4 +36,4 @@ def containsDuplicate(self, nums: List[int]) -> bool: if i in seen: return True seen.add(i) - return False \ No newline at end of file + return False From 100b8bbbe7df8b178fdcf8651f05ae193ce19bc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E1=84=8B=E1=85=B5=E1=84=8B=E1=85=A7=E1=86=AB=E1=84=89?= =?UTF-8?q?=E1=85=AE?= Date: Tue, 10 Dec 2024 13:02:18 +0900 Subject: [PATCH 149/396] =?UTF-8?q?Top=20K=20Frequent=20Element=20?= =?UTF-8?q?=ED=94=BC=EB=93=9C=EB=B0=B1=20=EB=B0=98=EC=98=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- top-k-frequent-elements/EcoFriendlyAppleSu.kt | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/top-k-frequent-elements/EcoFriendlyAppleSu.kt b/top-k-frequent-elements/EcoFriendlyAppleSu.kt index 952ff3318..ae971ae09 100644 --- a/top-k-frequent-elements/EcoFriendlyAppleSu.kt +++ b/top-k-frequent-elements/EcoFriendlyAppleSu.kt @@ -2,7 +2,7 @@ package leetcode_study /** * 주어진 숫자들에서 빈도 수가 가장 큰 k 개의 숫자를 구하는 문제. map 자료구조를 사용해 해결 - * 시간 복잡도 : O(n) + * 시간 복잡도 : O(nlogn) * -> Int Array를 순회해 map에 담는 과정 O(n) * -> 채워진 Map 자료구조에서 value 기준 내림차순으로 정렬 과정 O(nlogn) * -> 정렬된 Map에서 K 만큼 값을 가져오는 과정 O(K). (k는 상수) @@ -24,3 +24,39 @@ fun topKFrequent(nums: IntArray, k: Int): IntArray { val sortedMap = map.toList().sortedByDescending { it.second }.toMap() return sortedMap.entries.take(k).map { it.key }.toIntArray() } + +/** + * 주어진 수의 빈도수를 기준으로 숫자를 할당하고 내림차순으로 순회해 k 개의 숫자를 얻게 되면 답을 도출하는 방법 + * 시간 복잡도 : O(n) + * -> Int Array를 순회해 map에 담는 과정 O(n) + * -> 빈도수 배열에 값을 채우는 과정 O(n) + * -> 빈도수 배열을 내림차순으로 순회해 k 개를 만족하면 답을 도출하는 과정 O(n). + * 이중 for loop 이지만 실제로는 빈도수가 유일한 숫자들만 고려되므로 k가 n보다 작거나 같은 경우에는 O(n)으로 가늠할 수 있음. + * 각 단계의 시간 복잡도를 더하면 : O(n) + O(n) + O(n) -> O(n) + * 공간 복잡도 : O(n) + * -> Int Array에 존재하는 유니크한 요소 만큼 필요함. + */ +fun topKFrequent01(nums: IntArray, k: Int): IntArray { + val map = mutableMapOf() + for(num in nums) { + map[num] = map.getOrDefault(num, 0) + 1 + } + + // count List 초기화 + // map의 value는 nums Size를 넘을 수 없음. + val countList = Array(nums.size + 1) { mutableListOf() } + for ((key, value) in map) { + countList[value].add(key) + } + + val result = mutableListOf() + for (i in countList.size - 1 downTo 0) { + for (num in countList[i]) { + result.add(num) + if (result.size == k) { + return result.toIntArray() + } + } + } + return result.toIntArray() +} From 658b7780baa739ab1f307acce9358791cbbc35a7 Mon Sep 17 00:00:00 2001 From: mmyeon Date: Tue, 10 Dec 2024 13:25:23 +0900 Subject: [PATCH 150/396] add solution : 217. Contains Duplicate --- contains-duplicate/mmyeon.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 contains-duplicate/mmyeon.js diff --git a/contains-duplicate/mmyeon.js b/contains-duplicate/mmyeon.js new file mode 100644 index 000000000..a11188a21 --- /dev/null +++ b/contains-duplicate/mmyeon.js @@ -0,0 +1,24 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ + +/** + * + * 접근 방법 + * - Set 객체 사용해서 숫자 중복 제거하기 + * - 원본 배열과 길이 비교하기 + * + * 시간복잡도 : + * - 배열 순회해서 요소 Set에 삽입 : O(n) + * - Set의 사이즈 크기 비교 : O(1) + * + * 공간복잡도 : + * - Set에 유니크한 숫자 저장 : O(n) + */ + +var containsDuplicate = function (nums) { + const uniqueNumbers = new Set(nums); + + return uniqueNumbers.size !== nums.length; +}; From 04e234593df79cbec9a1122951d4563a1ba9eb4a Mon Sep 17 00:00:00 2001 From: mike2ox Date: Tue, 10 Dec 2024 14:37:04 +0900 Subject: [PATCH 151/396] feat: Upload top-k-frequent-element solution (typescript) --- top-k-frequent-elements/mike2ox.ts | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 top-k-frequent-elements/mike2ox.ts diff --git a/top-k-frequent-elements/mike2ox.ts b/top-k-frequent-elements/mike2ox.ts new file mode 100644 index 000000000..16b587600 --- /dev/null +++ b/top-k-frequent-elements/mike2ox.ts @@ -0,0 +1,22 @@ +/** + * Source: https://leetcode.com/problems/top-k-frequent-elements/ + * 풀이방법: 순회를 통해 빈도수를 저장, Object.entries를 통해 정렬하여 k개까지 반환 + * 시간복잡도: O(nlogn) + * 공간복잡도: O(n) + * + * 생각나는 풀이방법 + */ +function topKFrequent(nums: number[], k: number): number[] { + const KFrequentObject = new Object(); + const result = new Array(); + for (let num of nums) { + if (!Object.hasOwn(KFrequentObject, num)) KFrequentObject[num] = 0; + KFrequentObject[num]++; + } + // Object.entries를 통해 key, value를 배열로 반환 (포인트) + let sorted = Object.entries(KFrequentObject).sort((a, b) => b[1] - a[1]); + for (let node of sorted) { + result.push(parseInt(node[0])); + } + return result.slice(0, k); +} From 9eda1834ec6bc541b8723025d03c9c2f6e67718a Mon Sep 17 00:00:00 2001 From: Changhyun Lee Date: Tue, 10 Dec 2024 16:16:59 +0900 Subject: [PATCH 152/396] EDIT : Big-O --- contains-duplicate/heypaprika.py | 1 + house-robber/heypaprika.py | 1 + longest-consecutive-sequence/heypaprika.py | 1 + top-k-frequent-elements/heypaprika.py | 1 + valid-palindrome/heypaprika.py | 1 + 5 files changed, 5 insertions(+) diff --git a/contains-duplicate/heypaprika.py b/contains-duplicate/heypaprika.py index 2aa679a9b..dfa6d3123 100644 --- a/contains-duplicate/heypaprika.py +++ b/contains-duplicate/heypaprika.py @@ -1,3 +1,4 @@ +# Big-O 예상 : O(n*k) class Solution: def containsDuplicate(self, nums: List[int]) -> bool: num_dict = {} diff --git a/house-robber/heypaprika.py b/house-robber/heypaprika.py index 583399a1e..c62cbf0ec 100644 --- a/house-robber/heypaprika.py +++ b/house-robber/heypaprika.py @@ -1,3 +1,4 @@ +# Big-O 예상 : O(n) class Solution: def rob(self, nums: List[int]) -> int: a = [0] * len(nums) diff --git a/longest-consecutive-sequence/heypaprika.py b/longest-consecutive-sequence/heypaprika.py index a1f618d9a..6122ea730 100644 --- a/longest-consecutive-sequence/heypaprika.py +++ b/longest-consecutive-sequence/heypaprika.py @@ -1,3 +1,4 @@ +# Big-O 예상 : O(nlog(n)) class Solution: def longestConsecutive(self, nums: List[int]) -> int: nums = sorted(list(set(nums))) diff --git a/top-k-frequent-elements/heypaprika.py b/top-k-frequent-elements/heypaprika.py index bfd5996a8..c440d1f86 100644 --- a/top-k-frequent-elements/heypaprika.py +++ b/top-k-frequent-elements/heypaprika.py @@ -1,3 +1,4 @@ +# Big-O 예상 : O(nlog(n)) import heapq class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: diff --git a/valid-palindrome/heypaprika.py b/valid-palindrome/heypaprika.py index 41272ff9d..58463d55f 100644 --- a/valid-palindrome/heypaprika.py +++ b/valid-palindrome/heypaprika.py @@ -1,3 +1,4 @@ +# Big-O 예상 : O(n) class Solution: def isPalindrome(self, s: str) -> bool: s = "".join(s.lower().split(" ")) From 63441749896dc5b4df10217bcd01acc72b55cb90 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Tue, 10 Dec 2024 17:53:02 +0900 Subject: [PATCH 153/396] Add solution for Valid Palindrome problem --- valid-palindrome/KwonNayeon.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 valid-palindrome/KwonNayeon.py diff --git a/valid-palindrome/KwonNayeon.py b/valid-palindrome/KwonNayeon.py new file mode 100644 index 000000000..a05b33c05 --- /dev/null +++ b/valid-palindrome/KwonNayeon.py @@ -0,0 +1,24 @@ +""" +Title: 215. Valid Palindrome +Link: https://leetcode.com/problems/valid-palindrome/ + +Summary: + - Palindrome이라면 True, 아니라면 False를 반환하는 문제. + - Palindrome이란, 대문자를 소문자로 변환하고 알파벳과 숫자 이외의 문자를 제거한 후에도 + 앞으로 읽어도 뒤에서부터 읽어도 동일한 단어를 뜻함. + - e.g. racecar + +Conditions: + - 입력 문자열이 Palindrome인 경우: `True` 반환 + - Palindrome이 아닌 경우: `False` 반환 + +Time Complexity: + - O(n) +""" + +class Solution: + def isPalindrome(self, s: str) -> bool: + s = re.sub(r'[^a-zA-z]', '', s).lower() + if s == s[::-1]: + return True + return False From 365c1cc807eb019cc3c0348244596231d8d7b357 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Tue, 10 Dec 2024 18:02:56 +0900 Subject: [PATCH 154/396] Update description and conditions for Valid Palindrome problem --- valid-palindrome/KwonNayeon.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/valid-palindrome/KwonNayeon.py b/valid-palindrome/KwonNayeon.py index a05b33c05..71509b4ce 100644 --- a/valid-palindrome/KwonNayeon.py +++ b/valid-palindrome/KwonNayeon.py @@ -1,11 +1,11 @@ """ -Title: 215. Valid Palindrome +Title: 215. Valid Palindrome Link: https://leetcode.com/problems/valid-palindrome/ Summary: - Palindrome이라면 True, 아니라면 False를 반환하는 문제. - - Palindrome이란, 대문자를 소문자로 변환하고 알파벳과 숫자 이외의 문자를 제거한 후에도 - 앞으로 읽어도 뒤에서부터 읽어도 동일한 단어를 뜻함. + - Palindrome이란, 앞으로 읽어도 뒤에서부터 읽어도 동일한 단어를 뜻함. + - 추가 조건: 대소문자를 구분하지 않으며, 알파벳과 숫자 이외의 문자는 제거해야 함. - e.g. racecar Conditions: @@ -15,7 +15,6 @@ Time Complexity: - O(n) """ - class Solution: def isPalindrome(self, s: str) -> bool: s = re.sub(r'[^a-zA-z]', '', s).lower() From 29e30d2ae89f2ef9e792cf8d3cef94484a8c6b5b Mon Sep 17 00:00:00 2001 From: mike2ox Date: Tue, 10 Dec 2024 18:18:20 +0900 Subject: [PATCH 155/396] feat: Upload longest-consecutive-sequence solution (typescript) --- longest-consecutive-sequence/mike2ox.ts | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 longest-consecutive-sequence/mike2ox.ts diff --git a/longest-consecutive-sequence/mike2ox.ts b/longest-consecutive-sequence/mike2ox.ts new file mode 100644 index 000000000..697529d01 --- /dev/null +++ b/longest-consecutive-sequence/mike2ox.ts @@ -0,0 +1,32 @@ +/** + * Source: https://leetcode.com/problems/longest-consecutive-sequence/ + * 풀이방법: 정렬 후 순회를 통해 연속된 값이 있는지 확인 + * 시간복잡도: O(nlogn) + * 공간복잡도: O(1) + * + * 생각나는 풀이방법 + */ + +function longestConsecutive(nums: number[]): number { + if (nums.length === 0) return 0; + const sorted = nums.sort((a, b) => a - b); + let prev = sorted[0]; + let result = 1; + let candiResult = 1; + + for (let current of sorted) { + if (prev === current) continue; + if (current === prev + 1) { + candiResult += 1; + } else { + if (candiResult > result) { + result = candiResult; + } + candiResult = 1; + } + prev = current; + } + + if (candiResult > result) result = candiResult; + return result; +} From 5879dfdb12a3c5bf467160307eafa9450d659174 Mon Sep 17 00:00:00 2001 From: mike2ox Date: Tue, 10 Dec 2024 19:54:59 +0900 Subject: [PATCH 156/396] feat: Upload house-router solution (typescript) --- house-robber/mike2ox.ts | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 house-robber/mike2ox.ts diff --git a/house-robber/mike2ox.ts b/house-robber/mike2ox.ts new file mode 100644 index 000000000..ee95f4c3d --- /dev/null +++ b/house-robber/mike2ox.ts @@ -0,0 +1,24 @@ +/** + * Source: https://leetcode.com/problems/house-robber/ + * 풀이방법: DP를 이용하여 집을 털 때 최대값을 구함 + * 시간복잡도: O(n) + * 공간복잡도: O(n) + * + * 생각나는 풀이방법 + */ +function rob(nums: number[]): number { + if (nums.length === 0) return 0; + if (nums.length === 1) return nums[0]; + if (nums.length === 2) return Math.max(nums[0], nums[1]); + + const dp: number[] = new Array(nums.length); + + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + + // 남은 집을 순회하면서 최대값을 구함 + for (let i = 2; i < nums.length; i++) + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); + + return dp[nums.length - 1]; +} From 4f5f15e1e2f3cbf39f4c712eb57b804b62338126 Mon Sep 17 00:00:00 2001 From: Arthur Hwang Date: Tue, 10 Dec 2024 20:03:29 +0900 Subject: [PATCH 157/396] useless else Co-authored-by: Chaedong Im --- contains-duplicate/changchanghwang.go | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/contains-duplicate/changchanghwang.go b/contains-duplicate/changchanghwang.go index efa330024..fd655fd2d 100644 --- a/contains-duplicate/changchanghwang.go +++ b/contains-duplicate/changchanghwang.go @@ -8,9 +8,8 @@ func containsDuplicate(nums []int) bool { for _, num := range nums { if hashMap[num] { return true - } else { - hashMap[num] = true - } + } + hashMap[num] = true } return false } From 39be3890bb223d450ef5df099ec7077ea5b66562 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Tue, 10 Dec 2024 20:57:21 +0900 Subject: [PATCH 158/396] contains duplicate solution --- contains-duplicate/eunhwa99.java | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 contains-duplicate/eunhwa99.java diff --git a/contains-duplicate/eunhwa99.java b/contains-duplicate/eunhwa99.java new file mode 100644 index 000000000..ca29e9508 --- /dev/null +++ b/contains-duplicate/eunhwa99.java @@ -0,0 +1,14 @@ +class Solution { + public boolean containsDuplicate(int[] nums) { + HashSet seen = new HashSet<>(); + for (int num : nums) { + if (!seen.add(num)) { + return true; + } + } + + return false; + + + } +} From ff39fdec62cabc2508b12c45d627cb56ba62fc85 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Tue, 10 Dec 2024 21:07:08 +0900 Subject: [PATCH 159/396] valid palindrome solution --- valid-palindrome/eunhwa99.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 valid-palindrome/eunhwa99.java diff --git a/valid-palindrome/eunhwa99.java b/valid-palindrome/eunhwa99.java new file mode 100644 index 000000000..8af372df8 --- /dev/null +++ b/valid-palindrome/eunhwa99.java @@ -0,0 +1,23 @@ +class Solution { + public boolean isPalindrome(String s) { + StringBuilder str = new StringBuilder(); + + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (Character.isLetterOrDigit(c)) { + str.append(Character.toLowerCase(c)); + } + } + + int left = 0, right = str.length() - 1; + while (left < right) { + if (str.charAt(left) != str.charAt(right)) { + return false; + } + left++; + right--; + } + + return true; + } +} From 1774ef3b62cb85e8122316fd1b30906e5315e5aa Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Tue, 10 Dec 2024 22:01:59 +0900 Subject: [PATCH 160/396] [week1] valid-palindrome - gmlwls96 --- valid-palindrome/gmlwls96.kt | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 valid-palindrome/gmlwls96.kt diff --git a/valid-palindrome/gmlwls96.kt b/valid-palindrome/gmlwls96.kt new file mode 100644 index 000000000..e07183336 --- /dev/null +++ b/valid-palindrome/gmlwls96.kt @@ -0,0 +1,12 @@ +class Solution { + fun isPalindrome(s: String): Boolean { + val filterStr = s + .lowercase() + .filter { it in 'a'..'z' } + if (filterStr.isEmpty()) return true + for (i in 0..filterStr.lastIndex / 2) { + if (filterStr[i] != filterStr[filterStr.lastIndex - i]) return false + } + return true + } +} From ce6a63eba2ce97ed772cbfb9a557c1b5498e5f5f Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Tue, 10 Dec 2024 22:25:00 +0900 Subject: [PATCH 161/396] [week1] Top K Frequent Elements - gmlwls96 --- top-k-frequent-elements/gmlwls96.kt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 top-k-frequent-elements/gmlwls96.kt diff --git a/top-k-frequent-elements/gmlwls96.kt b/top-k-frequent-elements/gmlwls96.kt new file mode 100644 index 000000000..4a4ec7382 --- /dev/null +++ b/top-k-frequent-elements/gmlwls96.kt @@ -0,0 +1,15 @@ +class Solution { + fun topKFrequent(nums: IntArray, k: Int): IntArray { + val answer = IntArray(k) + val set = nums.toSet() + val mutableList = mutableListOf>() + set.forEach { num -> + mutableList.add(num to nums.count { it == num}) + } + mutableList.sortByDescending { it.second } + for (i in 0 until k){ + answer[i] = mutableList[i].first + } + return answer + } +} \ No newline at end of file From c17661ee263885b6373d89565399854f890afa4a Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Tue, 10 Dec 2024 23:05:48 +0900 Subject: [PATCH 162/396] contains duplicate solution --- contains-duplicate/YeomChaeEun.ts | 37 +++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 contains-duplicate/YeomChaeEun.ts diff --git a/contains-duplicate/YeomChaeEun.ts b/contains-duplicate/YeomChaeEun.ts new file mode 100644 index 000000000..91a455119 --- /dev/null +++ b/contains-duplicate/YeomChaeEun.ts @@ -0,0 +1,37 @@ +function containsDuplicate(nums: number[]): boolean { + + // 접근 (1) - 시간 복잡도가 매우 커서 실패 + // const uniqueArr = nums.filter((item, index) => { return nums.indexOf(item) === index }) + // console.log(uniqueArr) + // + // return nums.length !== uniqueArr.length; + + // 접근 (2) - 양 옆의 값을 비교 ============= + // if(nums.length === 1) + // return false; + // + // // 정렬 + // nums.sort() + // + // // 양 옆의 값을 비교 + // for(let i = 0; i < nums.length; i++){ + // console.log(nums[i], nums[i+1]) + // if(nums[i] === nums[i+1]){ + // return true; + // } + // } + // return false; + + // 접근 (3) - obj를 이용 ================ + let obj={} + + for(let i = 0; i < nums.length; i++) { + console.log('nums >>', nums[i], 'obj >>', obj) + if(obj[nums[i]]) { + return true; + } + obj[nums[i]] = 1; + } + return false; + +}; From 9f58fee3b531f4fa53e06be8269dbbf0ab076d69 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Tue, 10 Dec 2024 23:19:14 +0900 Subject: [PATCH 163/396] fix: change file name --- contains-duplicate/{YeomChaeEun.ts => chae.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{YeomChaeEun.ts => chae.ts} (100%) diff --git a/contains-duplicate/YeomChaeEun.ts b/contains-duplicate/chae.ts similarity index 100% rename from contains-duplicate/YeomChaeEun.ts rename to contains-duplicate/chae.ts From dca59258210d583627de777bb2b7750b3d75ce90 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Tue, 10 Dec 2024 23:22:18 +0900 Subject: [PATCH 164/396] fix: file name --- contains-duplicate/{chae.ts => YeomChaeeun.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{chae.ts => YeomChaeeun.ts} (100%) diff --git a/contains-duplicate/chae.ts b/contains-duplicate/YeomChaeeun.ts similarity index 100% rename from contains-duplicate/chae.ts rename to contains-duplicate/YeomChaeeun.ts From 4c42e811c4a4df00075bc173b5a5e46b9e2c4972 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=81=EC=9E=AC?= Date: Tue, 10 Dec 2024 23:47:08 +0900 Subject: [PATCH 165/396] add: solve #240 Longest Consecutive Sequence with ts --- longest-consecutive-sequence/YJason-K.ts | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 longest-consecutive-sequence/YJason-K.ts diff --git a/longest-consecutive-sequence/YJason-K.ts b/longest-consecutive-sequence/YJason-K.ts new file mode 100644 index 000000000..ceba08cd3 --- /dev/null +++ b/longest-consecutive-sequence/YJason-K.ts @@ -0,0 +1,40 @@ +/** + * 주어진 배열에서 가장 긴 연속된 숫자 시퀀스의 길이를 반환하는 함수 + * - 시간 복잡도: O(n) + * - O(n): Set에 숫자를 추가하고, 각 숫자를 순회하면서 연속된 시퀀스를 계산 + * - 공간 복잡도: O(n) + * - O(n): 숫자를 저장하기 위한 Set 사용 + * + * @param {number[]} nums - 정수 배열 + * @returns {number} - 가장 긴 연속된 숫자 시퀀스의 길이 + */ +function longestConsecutive(nums: number[]): number { + if (nums.length === 0) return 0; // 빈 배열 처리 (길이 0 반환) + + // 1. 배열을 Set에 저장하여 중복을 제거하고 빠른 조회를 가능하게 함 O(n) + const numSet = new Set(nums); + + let longestSeq = 0; // 가장 긴 연속 시퀀스 길이를 저장할 변수 + + // 2. 각 숫자가 시퀀스의 시작점인지 확인 + for (const num of numSet) { + // 숫자 `num`이 시퀀스의 시작점인지 확인 + // (num-1이 Set에 없다면 num은 시퀀스의 시작점) + if (!numSet.has(num - 1)) { + // 새로운 시퀀스 시작 + let curNum = num; + let curSeq = 1; + + // 3. 시퀀스가 끝날 때까지 길이를 계산 O(n) + while (numSet.has(curNum + 1)) { + curNum += 1; // 현재 숫자를 1 증가 + curSeq += 1; // 시퀀스 길이를 1 증가 + } + + // 4. 가장 긴 시퀀스 길이를 업데이트 + longestSeq = Math.max(longestSeq, curSeq); + } + } + + return longestSeq; // 가장 긴 연속 시퀀스의 길이 반환 +} From 408f184e520b713b97c15ada3aa5fc20b7be1dfb Mon Sep 17 00:00:00 2001 From: TotschKa Date: Mon, 9 Dec 2024 22:07:56 +0900 Subject: [PATCH 166/396] contains duplicate --- contains-duplicate/Totschka.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 contains-duplicate/Totschka.ts diff --git a/contains-duplicate/Totschka.ts b/contains-duplicate/Totschka.ts new file mode 100644 index 000000000..7c179787b --- /dev/null +++ b/contains-duplicate/Totschka.ts @@ -0,0 +1,12 @@ +// https://leetcode.com/problems/contains-duplicate/ +function containsDuplicate(nums: number[]): boolean { + const counter = {}; + for (const n of nums) { + if (!counter[n]) { + counter[n] = 1; + } else { + return true; + } + } + return false; +} From 6e44a93775c998532ebcd81f8de23cd8a0851992 Mon Sep 17 00:00:00 2001 From: TotschKa Date: Tue, 10 Dec 2024 01:22:44 +0900 Subject: [PATCH 167/396] valid palindrome --- valid-palindrome/Totschka.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 valid-palindrome/Totschka.ts diff --git a/valid-palindrome/Totschka.ts b/valid-palindrome/Totschka.ts new file mode 100644 index 000000000..1cbd6b48e --- /dev/null +++ b/valid-palindrome/Totschka.ts @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/valid-palindrome/description/ +function isPalindrome(s: string): boolean { + s = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); + for (let i = 0; i < s.length / 2; i++) { + if (s[i] !== s[s.length - 1 - i]) { + return false; + } + } + return true; +} From 8541dec58c410e8ef8644a0a8872aa150c7d98e8 Mon Sep 17 00:00:00 2001 From: TotschKa Date: Tue, 10 Dec 2024 23:32:53 +0900 Subject: [PATCH 168/396] top k frequent elements --- top-k-frequent-elements/Totschka.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 top-k-frequent-elements/Totschka.ts diff --git a/top-k-frequent-elements/Totschka.ts b/top-k-frequent-elements/Totschka.ts new file mode 100644 index 000000000..ecd54770e --- /dev/null +++ b/top-k-frequent-elements/Totschka.ts @@ -0,0 +1,10 @@ +// https://leetcode.com/problems/top-k-frequent-elements/ +function topKFrequent(nums: number[], k: number): number[] { + const counter = new Map(); + for (const n of nums) { + counter.set(n, (counter.get(n) ?? 0) + 1); + } + return [...counter.keys()] + .sort((a, b) => counter.get(b)! - counter.get(a)!) + .slice(0, k); +} From 4a27dad9f3972fe6756e3e08c24b77b2b62c02a5 Mon Sep 17 00:00:00 2001 From: pmjuu Date: Mon, 9 Dec 2024 13:55:08 -0500 Subject: [PATCH 169/396] feat: solve top k frequent elements --- top-k-frequent-elements/pmjuu.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 top-k-frequent-elements/pmjuu.py diff --git a/top-k-frequent-elements/pmjuu.py b/top-k-frequent-elements/pmjuu.py new file mode 100644 index 000000000..c1840cccb --- /dev/null +++ b/top-k-frequent-elements/pmjuu.py @@ -0,0 +1,24 @@ +from collections import Counter +from typing import List + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + # 빈도 계산 + count = Counter(nums) + n = len(nums) + + # 빈도수를 기준으로 버킷 생성 (0에서 n까지) + buckets = [[] for _ in range(n + 1)] + + # 각 숫자를 해당 빈도수의 버킷에 추가 + for num, freq in count.items(): + buckets[freq].append(num) + + # 빈도가 높은 순서대로 k개의 숫자를 추출 + result = [] + for freq in range(n, 0, -1): + if buckets[freq]: + result.extend(buckets[freq]) + + if len(result) == k: + return result From 9deb8d9c8dcc81eee8ccef8dc432faf43fb4aa21 Mon Sep 17 00:00:00 2001 From: Real-Reason Date: Wed, 11 Dec 2024 01:20:48 +0900 Subject: [PATCH 170/396] feat: longest-consecutive-sequence, top-k-frequent-elements solve --- longest-consecutive-sequence/Real-Reason.kt | 24 +++++++++++++++++++++ top-k-frequent-elements/Real-Reason.kt | 15 +++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 longest-consecutive-sequence/Real-Reason.kt create mode 100644 top-k-frequent-elements/Real-Reason.kt diff --git a/longest-consecutive-sequence/Real-Reason.kt b/longest-consecutive-sequence/Real-Reason.kt new file mode 100644 index 000000000..d0f1c2c29 --- /dev/null +++ b/longest-consecutive-sequence/Real-Reason.kt @@ -0,0 +1,24 @@ +package leetcode_study +class SolutionLongestConsecutiveSequence { + fun longestConsecutive(nums: IntArray): Int { + nums.sort() + var cnt = 0 + var maxCnt = 0 + nums.forEachIndexed { i, _ -> + if (i == 0) { + cnt = 1 + } + else if (nums[i-1] == nums[i] - 1) { + cnt++ + } + else if (nums[i - 1] == nums[i]) { + return@forEachIndexed + } else { + cnt = 1 + } + maxCnt = maxOf(maxCnt, cnt) + } + + return maxCnt + } +} diff --git a/top-k-frequent-elements/Real-Reason.kt b/top-k-frequent-elements/Real-Reason.kt new file mode 100644 index 000000000..b88a28641 --- /dev/null +++ b/top-k-frequent-elements/Real-Reason.kt @@ -0,0 +1,15 @@ +package leetcode_study +class SolutionTopKFrequentElements { + fun topKFrequent(nums: IntArray, k: Int): IntArray { + val numsCount = mutableMapOf() + for (num in nums) { + val value = numsCount.getOrDefault(num, 0) + numsCount[num] = value + 1 + } + val sortedNumsCount = numsCount.entries + .sortedByDescending { it.value } + .associate { it.toPair() } + + return sortedNumsCount.keys.take(k).toIntArray() + } +} From b4cb47c79a7ef44ede83276bc5590a57caa62733 Mon Sep 17 00:00:00 2001 From: pmjuu Date: Tue, 10 Dec 2024 15:18:35 -0500 Subject: [PATCH 171/396] feat: solve longest-consecutive-sequence --- longest-consecutive-sequence/pmjuu.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 longest-consecutive-sequence/pmjuu.py diff --git a/longest-consecutive-sequence/pmjuu.py b/longest-consecutive-sequence/pmjuu.py new file mode 100644 index 000000000..fe350077c --- /dev/null +++ b/longest-consecutive-sequence/pmjuu.py @@ -0,0 +1,22 @@ +from typing import List + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + # Convert to set for O(1) lookups + num_set = set(nums) + longest_length = 0 + + for num in num_set: + # Only start counting if num is the start of a sequence + if num - 1 not in num_set: + current_num = num + current_length = 1 + + # Count the length of the sequence + while current_num + 1 in num_set: + current_num += 1 + current_length += 1 + + longest_length = max(longest_length, current_length) + + return longest_length From 9bfe355e174c884a03a6cfe07d4a98316b16dc2d Mon Sep 17 00:00:00 2001 From: easyone Date: Wed, 11 Dec 2024 08:06:14 +0900 Subject: [PATCH 172/396] Feat: Add solution of top-k-frequent-elements --- top-k-frequent-elements/easyone-jwlee.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 top-k-frequent-elements/easyone-jwlee.go diff --git a/top-k-frequent-elements/easyone-jwlee.go b/top-k-frequent-elements/easyone-jwlee.go new file mode 100644 index 000000000..5a024515b --- /dev/null +++ b/top-k-frequent-elements/easyone-jwlee.go @@ -0,0 +1,20 @@ +func topKFrequent(nums []int, k int) []int { + m := make(map[int]int) + for _, num := range nums { + m[num]++ + } + a := make([][]int, len(nums)+1) + for key, num := range m { + a[num] = append(a[num], key) + } + result := make([]int, 0) + for i := cap(a) - 1; i >= 0; i-- { + if len(a[i]) > 0 { + result = append(result, a[i]...) + } + if len(result) == k { + break + } + } + return result +} From 912848ae31eda3836ee5325d24aba319b3b28b9f Mon Sep 17 00:00:00 2001 From: gmlwls96 Date: Wed, 11 Dec 2024 08:35:23 +0900 Subject: [PATCH 173/396] =?UTF-8?q?=EC=A4=84=EB=B0=94=EA=BF=88=20=EB=88=84?= =?UTF-8?q?=EB=9D=BD=20=EC=B2=98=EB=A6=AC=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- top-k-frequent-elements/gmlwls96.kt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/top-k-frequent-elements/gmlwls96.kt b/top-k-frequent-elements/gmlwls96.kt index 4a4ec7382..2294a224f 100644 --- a/top-k-frequent-elements/gmlwls96.kt +++ b/top-k-frequent-elements/gmlwls96.kt @@ -2,14 +2,14 @@ class Solution { fun topKFrequent(nums: IntArray, k: Int): IntArray { val answer = IntArray(k) val set = nums.toSet() - val mutableList = mutableListOf>() + val mutableList = mutableListOf>() set.forEach { num -> - mutableList.add(num to nums.count { it == num}) + mutableList.add(num to nums.count { it == num }) } mutableList.sortByDescending { it.second } - for (i in 0 until k){ + for (i in 0 until k) { answer[i] = mutableList[i].first } return answer } -} \ No newline at end of file +} From 7d3bd3a86432353ab8af68207212d892a013fb81 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Tue, 10 Dec 2024 15:54:34 -0800 Subject: [PATCH 174/396] contains-duplicate solution --- contains-duplicate/Zioq.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 contains-duplicate/Zioq.js diff --git a/contains-duplicate/Zioq.js b/contains-duplicate/Zioq.js new file mode 100644 index 000000000..86cf6198d --- /dev/null +++ b/contains-duplicate/Zioq.js @@ -0,0 +1,28 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + let dup_set = new Set(); // Initialize Set + for (let num of nums) { + dup_set.add(num) // Add value into the set (duplicated value will be ignored) + } + + if(dup_set.size !== nums.length) { + return true + } + return false +}; + +/* + Space Complexity - O(n) - Create a set to store elements + Time Complexity - O(n) - Traverse through the array +*/ + + +/* Test code */ +console.log(containsDuplicate([1, 2, 3, 1])); // true +console.log(containsDuplicate([1, 2, 3, 4])); // false +console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); // true + + From cd0087a36aa693111a6aa34f22dccb117dd38504 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Tue, 10 Dec 2024 15:55:31 -0800 Subject: [PATCH 175/396] top-k-frequent-elements solution --- top-k-frequent-elements/Zioq.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 top-k-frequent-elements/Zioq.js diff --git a/top-k-frequent-elements/Zioq.js b/top-k-frequent-elements/Zioq.js new file mode 100644 index 000000000..d24310275 --- /dev/null +++ b/top-k-frequent-elements/Zioq.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + + const map = new Map(); + let arr = [] + + nums.forEach( e => { + if(map.has(e)) { + let current_value = map.get(e) + map.set(e, current_value +1) + } else { + map.set(e, 1) + } + }) + const store = [...map.entries()].sort((a,b) => b[1] - a[1]) + for( let i = 0 ; i < k && i < store.length ; i++ ) { + arr.push(store[i][0]) + } + return arr + +}; + + +/* Test code */ +console.log(topKFrequent([1,1,1,2,2,3],2)); // true +console.log(topKFrequent([1,2],1)); // true From cf8bb2900000a86790a09d4fd8f30c9fe76d0a3a Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Tue, 10 Dec 2024 15:55:59 -0800 Subject: [PATCH 176/396] valid-palindrome solution --- valid-palindrome/Zioq.js | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 valid-palindrome/Zioq.js diff --git a/valid-palindrome/Zioq.js b/valid-palindrome/Zioq.js new file mode 100644 index 000000000..36fce16fb --- /dev/null +++ b/valid-palindrome/Zioq.js @@ -0,0 +1,33 @@ +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + + let text = s.replace(/[^0-9a-z]/gi, ''); + text = text.replace(/\s/g, '').toLowerCase(); + + const str_arr = text.split(""); + if( str_arr % 2 === 1 ) { + return false; + } + + let length = str_arr.length - 1 ; + for ( const [i, value] of str_arr.entries()) { + if( value == str_arr[length -i] ) continue; + if(value != str_arr[length - i]) { + return false + } + } + return true; +}; + +/* + Space Complexity - O(n) - Create a array to store elements + Time Complexity - O(n) - Traverse through the array +*/ + +/* Test code */ +console.log(isPalindrome("A man, a plan, a canal: Panama")); // true +console.log(isPalindrome("race a car")); // false +console.log(isPalindrome(" ")); // true From 1b3d9a0f6915b8837f393dfd4b0ebc57efe008b0 Mon Sep 17 00:00:00 2001 From: Paik Date: Wed, 11 Dec 2024 09:15:55 +0900 Subject: [PATCH 177/396] feat: 128. Longest Consecutive Sequence --- longest-consecutive-sequence/gwbaik9717.js | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 longest-consecutive-sequence/gwbaik9717.js diff --git a/longest-consecutive-sequence/gwbaik9717.js b/longest-consecutive-sequence/gwbaik9717.js new file mode 100644 index 000000000..0835fba7e --- /dev/null +++ b/longest-consecutive-sequence/gwbaik9717.js @@ -0,0 +1,30 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + let answer = 0; + const consecutiveDict = new Map(); + + for (const num of nums) { + consecutiveDict.set(num, true); + } + + for (const num of nums) { + if (consecutiveDict.has(num - 1)) { + continue; + } + + let length = 1; + while (consecutiveDict.has(num + length)) { + length++; + } + + answer = Math.max(answer, length); + } + + return answer; +}; From c299218f38beac10bcbc4c475262893c8ae7945c Mon Sep 17 00:00:00 2001 From: gmlwls96 Date: Wed, 11 Dec 2024 10:37:18 +0900 Subject: [PATCH 178/396] [week1] Longest-consecutive-sequence - gmlwls96 --- longest-consecutive-sequence/gmlwls96.kt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 longest-consecutive-sequence/gmlwls96.kt diff --git a/longest-consecutive-sequence/gmlwls96.kt b/longest-consecutive-sequence/gmlwls96.kt new file mode 100644 index 000000000..d0d78ce8a --- /dev/null +++ b/longest-consecutive-sequence/gmlwls96.kt @@ -0,0 +1,18 @@ +package leetcode_study + +class Solution { + fun longestConsecutive(nums: IntArray): Int { + nums.sort() + val consecutiveArray = IntArray(nums.size) + var maxCount = 0 + for (i in nums.lastIndex - 1 downTo (0)) { + if (nums[i] + 1 == nums[i + 1]) { + consecutiveArray[i] += consecutiveArray[i + 1] + 1 + if (consecutiveArray[i] > maxCount) { + maxCount = consecutiveArray[i] + } + } + } + return maxCount + 1 + } +} From 4247144adb74338fe9f3ebdcb4d662e6dfa607fa Mon Sep 17 00:00:00 2001 From: gmlwls96 Date: Wed, 11 Dec 2024 10:47:03 +0900 Subject: [PATCH 179/396] [week1] House Robber - gmlwls96 --- house-robber/gmlwls96.kt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 house-robber/gmlwls96.kt diff --git a/house-robber/gmlwls96.kt b/house-robber/gmlwls96.kt new file mode 100644 index 000000000..154d97fce --- /dev/null +++ b/house-robber/gmlwls96.kt @@ -0,0 +1,16 @@ +package leetcode_study + +import java.lang.Integer.max + +class Solution { + fun rob(nums: IntArray): Int { + return max(rob_recursion(nums, 0), rob_recursion(nums, 1)) + } + + private fun rob_recursion(nums: IntArray, index: Int): Int { + if (index >= nums.size) { + return 0 + } + return nums[index] + rob_recursion(nums, index + 2) + } +} From e4c38400d0b13935c797ccfad8be6f98d66629d1 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Tue, 10 Dec 2024 18:05:53 -0800 Subject: [PATCH 180/396] longest-consecutive-sequence solution --- longest-consecutive-sequence/Zioq.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 longest-consecutive-sequence/Zioq.js diff --git a/longest-consecutive-sequence/Zioq.js b/longest-consecutive-sequence/Zioq.js new file mode 100644 index 000000000..5058244e1 --- /dev/null +++ b/longest-consecutive-sequence/Zioq.js @@ -0,0 +1,25 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function(nums) { + if(nums.length === 0) return 0 + let set = new Set(); + for(const n of nums) { + set.add(n); + } + let max = 0; + for(let n of set) { + if(!set.has(n-1)) { + let count = 0; + while(set.has(n++)) { + count++; + } + max = Math.max(max, count); + } + } + return max; +}; + +/* Test code */ +console.log(longestConsecutive([9,1,4,7,3,-1,0,5,8,-1,6])); // true \ No newline at end of file From 88ef3903cfa582e91e16b0b613f2a0aeb9b08551 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Tue, 10 Dec 2024 18:08:55 -0800 Subject: [PATCH 181/396] update last line --- longest-consecutive-sequence/Zioq.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/longest-consecutive-sequence/Zioq.js b/longest-consecutive-sequence/Zioq.js index 5058244e1..a563f0575 100644 --- a/longest-consecutive-sequence/Zioq.js +++ b/longest-consecutive-sequence/Zioq.js @@ -22,4 +22,4 @@ var longestConsecutive = function(nums) { }; /* Test code */ -console.log(longestConsecutive([9,1,4,7,3,-1,0,5,8,-1,6])); // true \ No newline at end of file +console.log(longestConsecutive([9,1,4,7,3,-1,0,5,8,-1,6])); // true From 46b8f2abc55b9ffca0915875b2eb527db3cbca4f Mon Sep 17 00:00:00 2001 From: HiGeuni Date: Wed, 11 Dec 2024 11:32:31 +0900 Subject: [PATCH 182/396] Add solutions : Week 1 --- contains-duplicate/khyo.js | 9 ++++++ house-robber/khyo.js | 25 +++++++++++++++ longest-common-subsequence/khyo.js | 49 ++++++++++++++++++++++++++++++ top-k-frequent-elements/khyo.js | 25 +++++++++++++++ valid-palindrome/khyo.js | 23 ++++++++++++++ 5 files changed, 131 insertions(+) create mode 100644 contains-duplicate/khyo.js create mode 100644 house-robber/khyo.js create mode 100644 longest-common-subsequence/khyo.js create mode 100644 top-k-frequent-elements/khyo.js create mode 100644 valid-palindrome/khyo.js diff --git a/contains-duplicate/khyo.js b/contains-duplicate/khyo.js new file mode 100644 index 000000000..850fb8b72 --- /dev/null +++ b/contains-duplicate/khyo.js @@ -0,0 +1,9 @@ +// 풀이 +// Set으로 중복 제거 후 nums와 길이 비교 + +// TC : O(N) +// SC : O(N) + +var containsDuplicate = function(nums) { + return new Set(nums).size !== nums.length +}; diff --git a/house-robber/khyo.js b/house-robber/khyo.js new file mode 100644 index 000000000..18d882ac9 --- /dev/null +++ b/house-robber/khyo.js @@ -0,0 +1,25 @@ +// 풀이 +// dp를 이용한 풀이 +// 점화식 : dp[index] = Math.max(dp[index-1], dp[index-2] + nums[index]) +// 사용되는 변수가 index-1, index-2 뿐이라 불필요한 배열을 제거하고자 함. + +// TC : O(N) +// SC : O(1) + +var rob = function(nums) { + let dp = new Array(2); + + dp[0] = nums[0] + // nums의 길이가 1인 경우 예외처리 + dp[1] = nums.length > 1 ? Math.max(nums[0], nums[1]) : nums[0] + + nums.forEach((num, index) => { + if(index <= 1) return; + + let temp = Math.max(dp[1], dp[0] + nums[index]) + dp[0] = dp[1] + dp[1] = temp + }) + + return dp[1] +}; diff --git a/longest-common-subsequence/khyo.js b/longest-common-subsequence/khyo.js new file mode 100644 index 000000000..a2543d1a6 --- /dev/null +++ b/longest-common-subsequence/khyo.js @@ -0,0 +1,49 @@ +// 정렬을 이용한 풀이 +// TC : O(NlogN) +// SC : O(N) + +var longestConsecutiveUsingSort = function (nums) { + if (nums.length === 0) return 0; + + const uniqueNums = [...new Set(nums)].sort((a, b) => a - b); + + let max_cnt = 0; + let cnt = 1; + for (let i = 1; i < uniqueNums.length; ++i) { + if (uniqueNums[i - 1] + 1 == uniqueNums[i]) { + cnt += 1; + } else { + max_cnt = cnt > max_cnt ? cnt : max_cnt; + cnt = 1; + } + } + max_cnt = cnt > max_cnt ? cnt : max_cnt; + return max_cnt; +}; + +// 집합을 이용한 풀이 +// TC : O(N) +// SC : O(N) + +var longestConsecutive = function (nums) { + if (nums.length === 0) return 0; + + const numSet = new Set(nums); + let maxLength = 0; + + for (const num of numSet) { + if (!numSet.has(num - 1)) { + let currentNum = num; + let currentLength = 1; + + while (numSet.has(currentNum + 1)) { + currentNum++; + currentLength++; + } + + maxLength = Math.max(maxLength, currentLength); + } + } + + return maxLength; +}; diff --git a/top-k-frequent-elements/khyo.js b/top-k-frequent-elements/khyo.js new file mode 100644 index 000000000..023716b0a --- /dev/null +++ b/top-k-frequent-elements/khyo.js @@ -0,0 +1,25 @@ +// 풀이 +// 1. 각 요소의 빈도를 계산하여 countObject 생성 +// 2. countObject를 정렬하여 상위 k개의 요소 추출 +// 3. 추출된 요소를 배열로 반환 + +// TC : O(NlogN) +// SC : O(N) + +var topKFrequent = function(nums, k) { + const countObject = {} + nums.map((num) => { + if(countObject[num]) { + countObject[num] += 1 + }else { + countObject[num] = 1 + } + }) + + const sortedObject = Object.entries(countObject) + .sort((a,b) => b[1] - a[1]) + .slice(0, k) + .map(item => Number(item[0])) + + return sortedObject +}; diff --git a/valid-palindrome/khyo.js b/valid-palindrome/khyo.js new file mode 100644 index 000000000..568f7f486 --- /dev/null +++ b/valid-palindrome/khyo.js @@ -0,0 +1,23 @@ +// 풀이 +// 1. 영어, 숫자만 남기고 소문자로 변환한 newStr 생성 +// 2. 투포인터를 이용해 문자열 팰린드롬 여부 확인 (초기값 : true) +// 3. 중간에 팰린드롬이 아닌 지점을 발견하면 flag를 false로 변경 후 return + +// TC : O(N) +// SC : O(N) + +var isPalindrome = function(s) { + const newStr = s.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); + let flag = true + let left = 0, right = newStr.length - 1 + while(left < right){ + if(newStr[left] === newStr[right]) { + left += 1; + right -= 1; + }else { + flag = false; + break; + } + } + return flag +}; From e43d056dd8da59179f37a583b39a4cd06dd672ce Mon Sep 17 00:00:00 2001 From: HiGeuni Date: Wed, 11 Dec 2024 11:46:19 +0900 Subject: [PATCH 183/396] fix : add '\n' --- contains-duplicate/khyo.js | 1 + house-robber/khyo.js | 1 + longest-common-subsequence/khyo.js | 1 + top-k-frequent-elements/khyo.js | 1 + valid-palindrome/khyo.js | 1 + 5 files changed, 5 insertions(+) diff --git a/contains-duplicate/khyo.js b/contains-duplicate/khyo.js index 850fb8b72..e5bd164dc 100644 --- a/contains-duplicate/khyo.js +++ b/contains-duplicate/khyo.js @@ -7,3 +7,4 @@ var containsDuplicate = function(nums) { return new Set(nums).size !== nums.length }; + diff --git a/house-robber/khyo.js b/house-robber/khyo.js index 18d882ac9..2ddaafeb4 100644 --- a/house-robber/khyo.js +++ b/house-robber/khyo.js @@ -23,3 +23,4 @@ var rob = function(nums) { return dp[1] }; + diff --git a/longest-common-subsequence/khyo.js b/longest-common-subsequence/khyo.js index a2543d1a6..1d56fd8ba 100644 --- a/longest-common-subsequence/khyo.js +++ b/longest-common-subsequence/khyo.js @@ -47,3 +47,4 @@ var longestConsecutive = function (nums) { return maxLength; }; + diff --git a/top-k-frequent-elements/khyo.js b/top-k-frequent-elements/khyo.js index 023716b0a..19d4d56e7 100644 --- a/top-k-frequent-elements/khyo.js +++ b/top-k-frequent-elements/khyo.js @@ -23,3 +23,4 @@ var topKFrequent = function(nums, k) { return sortedObject }; + diff --git a/valid-palindrome/khyo.js b/valid-palindrome/khyo.js index 568f7f486..857350721 100644 --- a/valid-palindrome/khyo.js +++ b/valid-palindrome/khyo.js @@ -21,3 +21,4 @@ var isPalindrome = function(s) { } return flag }; + From 3e4997093f2ba0c807d6dbb750941a5cba80224f Mon Sep 17 00:00:00 2001 From: HiGeuni Date: Wed, 11 Dec 2024 11:57:24 +0900 Subject: [PATCH 184/396] change : file name --- contains-duplicate/{khyo.js => higeuni.js} | 0 house-robber/{khyo.js => higeuni.js} | 0 longest-common-subsequence/{khyo.js => higeuni.js} | 0 top-k-frequent-elements/{khyo.js => higeuni.js} | 0 valid-palindrome/{khyo.js => higeuni.js} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{khyo.js => higeuni.js} (100%) rename house-robber/{khyo.js => higeuni.js} (100%) rename longest-common-subsequence/{khyo.js => higeuni.js} (100%) rename top-k-frequent-elements/{khyo.js => higeuni.js} (100%) rename valid-palindrome/{khyo.js => higeuni.js} (100%) diff --git a/contains-duplicate/khyo.js b/contains-duplicate/higeuni.js similarity index 100% rename from contains-duplicate/khyo.js rename to contains-duplicate/higeuni.js diff --git a/house-robber/khyo.js b/house-robber/higeuni.js similarity index 100% rename from house-robber/khyo.js rename to house-robber/higeuni.js diff --git a/longest-common-subsequence/khyo.js b/longest-common-subsequence/higeuni.js similarity index 100% rename from longest-common-subsequence/khyo.js rename to longest-common-subsequence/higeuni.js diff --git a/top-k-frequent-elements/khyo.js b/top-k-frequent-elements/higeuni.js similarity index 100% rename from top-k-frequent-elements/khyo.js rename to top-k-frequent-elements/higeuni.js diff --git a/valid-palindrome/khyo.js b/valid-palindrome/higeuni.js similarity index 100% rename from valid-palindrome/khyo.js rename to valid-palindrome/higeuni.js From 7fe96f43f5b1dff21c6ed46cc32bb7d1ead2fb46 Mon Sep 17 00:00:00 2001 From: Suha Date: Tue, 10 Dec 2024 23:28:13 -0400 Subject: [PATCH 185/396] contains duplicate solution --- contains-duplicate/suhacs.js | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 contains-duplicate/suhacs.js diff --git a/contains-duplicate/suhacs.js b/contains-duplicate/suhacs.js new file mode 100644 index 000000000..d85e0837d --- /dev/null +++ b/contains-duplicate/suhacs.js @@ -0,0 +1,9 @@ +function containsDuplicate(nums) { + const setLength = [...new Set(nums)].length; + const numLength = nums.length; + + if (numLength === setLength) return false; + else return true; +} + +console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); From 5c3e52547d6da210130561437724b49ec2b9306f Mon Sep 17 00:00:00 2001 From: Suha Date: Tue, 10 Dec 2024 23:53:22 -0400 Subject: [PATCH 186/396] contains duplicate solution --- contains-duplicate/suhacs.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contains-duplicate/suhacs.js b/contains-duplicate/suhacs.js index d85e0837d..a433866d5 100644 --- a/contains-duplicate/suhacs.js +++ b/contains-duplicate/suhacs.js @@ -7,3 +7,5 @@ function containsDuplicate(nums) { } console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); + +// From 52125486138aa0114b94f3508af207e1863a2582 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Wed, 11 Dec 2024 12:55:33 +0900 Subject: [PATCH 187/396] Solved 237. Top K Frequent Elements problem --- top-k-frequent-elements/KwonNayeon.py | 33 +++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 top-k-frequent-elements/KwonNayeon.py diff --git a/top-k-frequent-elements/KwonNayeon.py b/top-k-frequent-elements/KwonNayeon.py new file mode 100644 index 000000000..3dc9d1fe6 --- /dev/null +++ b/top-k-frequent-elements/KwonNayeon.py @@ -0,0 +1,33 @@ +""" +Title: 237. Top K Frequent Elements +Link: https://leetcode.com/problems/top-k-frequent-elements/ + +Question: + - Given an integer array `nums` and an integer `k`, return the `k` most frequent elements. + - You may return the answer in any order. + +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]. + - The answer is guaranteed to be unique. + +Time Complexity: + - O(n log n) +Space Complexity: + - O(n) +""" + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + frequency = {} + result = [] + for num in nums: + if num in frequency: + frequency[num] += 1 + else: + frequency[num] = 1 + sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse=True) + for i in range(k): + result.append(sorted_frequency[i][0]) + return result \ No newline at end of file From 228f63b1876186351752234b811bb13cfc337183 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Wed, 11 Dec 2024 12:56:40 +0900 Subject: [PATCH 188/396] Add newline at the end of the file to comply with the CI requirements --- top-k-frequent-elements/KwonNayeon.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/top-k-frequent-elements/KwonNayeon.py b/top-k-frequent-elements/KwonNayeon.py index 3dc9d1fe6..401538132 100644 --- a/top-k-frequent-elements/KwonNayeon.py +++ b/top-k-frequent-elements/KwonNayeon.py @@ -30,4 +30,5 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]: sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse=True) for i in range(k): result.append(sorted_frequency[i][0]) - return result \ No newline at end of file + return result + \ No newline at end of file From 892a2792644b284fcb44db4392a0bf8c5e3f0c1b Mon Sep 17 00:00:00 2001 From: Suha Date: Tue, 10 Dec 2024 23:57:33 -0400 Subject: [PATCH 189/396] contains duplicate solution --- contains-duplicate/suhacs.js | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/contains-duplicate/suhacs.js b/contains-duplicate/suhacs.js index a433866d5..75481ee49 100644 --- a/contains-duplicate/suhacs.js +++ b/contains-duplicate/suhacs.js @@ -1,3 +1,16 @@ +/** + * @description + * time complexity: O(n) + * space complexity: O(n) + * approach/strategy: + * 1. brute force + hash table + */ + +/** + * @param {number[]} nums + * @return {boolean} + */ + function containsDuplicate(nums) { const setLength = [...new Set(nums)].length; const numLength = nums.length; From a4fa1ea0e9387258e4c786e37d6415f9bd42650f Mon Sep 17 00:00:00 2001 From: Nayeon Date: Wed, 11 Dec 2024 12:59:13 +0900 Subject: [PATCH 190/396] Fix: remove unnecessary spaces before newline to comply with CI requirements --- top-k-frequent-elements/KwonNayeon.py | 1 - 1 file changed, 1 deletion(-) diff --git a/top-k-frequent-elements/KwonNayeon.py b/top-k-frequent-elements/KwonNayeon.py index 401538132..cdfab0b31 100644 --- a/top-k-frequent-elements/KwonNayeon.py +++ b/top-k-frequent-elements/KwonNayeon.py @@ -31,4 +31,3 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]: for i in range(k): result.append(sorted_frequency[i][0]) return result - \ No newline at end of file From 7fee1c6e6ab5a671e455ab25f7efd4d2d0e41437 Mon Sep 17 00:00:00 2001 From: choidabom Date: Wed, 11 Dec 2024 14:30:46 +0900 Subject: [PATCH 191/396] 217. Contains Duplicate --- contains-duplicate/choidabom.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 contains-duplicate/choidabom.js diff --git a/contains-duplicate/choidabom.js b/contains-duplicate/choidabom.js new file mode 100644 index 000000000..a5de8360c --- /dev/null +++ b/contains-duplicate/choidabom.js @@ -0,0 +1,17 @@ +/** + * Runtime: 17ms, Memory: 63.18MB + * + * Time Complexity: O(n) + * - Array to Set takes O(n) + * - Compare Set size and array length takes O(1) + * Space Complexity: O(n) + * - Space for Set : O(n) +*/ + +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + return new Set(nums).size !== nums.length +}; \ No newline at end of file From 2e471ad00ca5e71815b5ef46fbdef6f68fcfdf90 Mon Sep 17 00:00:00 2001 From: choidabom Date: Wed, 11 Dec 2024 14:42:40 +0900 Subject: [PATCH 192/396] =?UTF-8?q?fix:=20lint=20error=20(=EC=A4=84?= =?UTF-8?q?=EB=B0=94=EA=BF=88)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/choidabom.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/choidabom.js b/contains-duplicate/choidabom.js index a5de8360c..9d21f159e 100644 --- a/contains-duplicate/choidabom.js +++ b/contains-duplicate/choidabom.js @@ -14,4 +14,4 @@ */ var containsDuplicate = function(nums) { return new Set(nums).size !== nums.length -}; \ No newline at end of file +}; From 70c59be8287cdb824c80280744cb00bc7d8ab8ac Mon Sep 17 00:00:00 2001 From: HiGeuni Date: Wed, 11 Dec 2024 16:16:05 +0900 Subject: [PATCH 193/396] fix: move file to longest-consecutive-sequence --- .../higeuni.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {longest-common-subsequence => longest-consecutive-sequence}/higeuni.js (100%) diff --git a/longest-common-subsequence/higeuni.js b/longest-consecutive-sequence/higeuni.js similarity index 100% rename from longest-common-subsequence/higeuni.js rename to longest-consecutive-sequence/higeuni.js From 2db6f2c438000744bce81748b869c48aefee94d7 Mon Sep 17 00:00:00 2001 From: HiGeuni Date: Wed, 11 Dec 2024 16:17:37 +0900 Subject: [PATCH 194/396] fix: map to forEach --- top-k-frequent-elements/higeuni.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/top-k-frequent-elements/higeuni.js b/top-k-frequent-elements/higeuni.js index 19d4d56e7..a88642d6f 100644 --- a/top-k-frequent-elements/higeuni.js +++ b/top-k-frequent-elements/higeuni.js @@ -8,7 +8,7 @@ var topKFrequent = function(nums, k) { const countObject = {} - nums.map((num) => { + nums.forEach((num) => { if(countObject[num]) { countObject[num] += 1 }else { From df0d71c109ade97727e30a0f220afd23e18fe066 Mon Sep 17 00:00:00 2001 From: aa601 Date: Wed, 11 Dec 2024 17:47:17 +0900 Subject: [PATCH 195/396] contains-duplicate --- contains-duplicate/aa601.c | 60 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 contains-duplicate/aa601.c diff --git a/contains-duplicate/aa601.c b/contains-duplicate/aa601.c new file mode 100644 index 000000000..c0c3c52a1 --- /dev/null +++ b/contains-duplicate/aa601.c @@ -0,0 +1,60 @@ +#include +#include + +void merge(int *nums, int left, int mid, int right) +{ + int i; + int j; + int k; + int leftArr[mid - left + 1]; + int rightArr[right - mid]; + + i = -1; + while (++i < mid - left + 1) // 왼쪽 분할된 부분 넣기 + leftArr[i] = nums[left + i]; + i = -1; + while (++i < right - mid) // 오른쪽 분할된 부분 넣기 + rightArr[i] = nums[mid + i + 1]; + i = 0; + j = 0; + k = left; // **** nums배열인덱스 => left부터 시작 + // 나누어진 배열끼리 비교해서 nums배열 재배치 + while ((i < mid - left + 1) && (j < right - mid)) { + if (leftArr[i] <= rightArr[j]) + nums[k] = leftArr[i++]; + else + nums[k] = rightArr[j++]; + ++k; + } + while (i < mid - left + 1) // left배열 남아있으면 마저 삽입 + nums[k++] = leftArr[i++]; + while (j < right - mid) // right배열 남아있으면 마저 삽입 + nums[k++] = rightArr[j++]; +} + +void mergeSort(int *nums, int left, int right) { + int mid; + + if (left < right) + { + mid = (left + right) / 2; + mergeSort(nums, left, mid); // 왼쪽분할 + mergeSort(nums, mid + 1, right); // 오른쪽분할 + merge(nums, left, mid, right); + } +} + +bool containsDuplicate(int* nums, int numsSize) { + int i; + + mergeSort(nums, 0, numsSize - 1); + i = -1; + while (++i + 1 < numsSize) { + if (nums[i] == nums[i + 1]) + return (true); + } + return (false); +} + + + From d90dfc2eb1cf77f77e5d491bf9cffd433c500565 Mon Sep 17 00:00:00 2001 From: sungjinwi <0202wsj@gmail.com> Date: Wed, 11 Dec 2024 17:56:21 +0900 Subject: [PATCH 196/396] valid-palindrome solution && complexity calc --- valid-palindrome/sungjinwi.c | 51 ++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 valid-palindrome/sungjinwi.c diff --git a/valid-palindrome/sungjinwi.c b/valid-palindrome/sungjinwi.c new file mode 100644 index 000000000..1bd4a4565 --- /dev/null +++ b/valid-palindrome/sungjinwi.c @@ -0,0 +1,51 @@ +#include +#include +#include +#include + +/* + 문자열 s의 길이를 N이라고 할 때 + + 시간복잡도 + + for문 두 번 돌려서 2N + + => N +================= + 공간복잡도 + + 두 번 복사하면서 2N + + => N +*/ + +bool isPalindrome(char* s) { + char *alnumDup = calloc(strlen(s) + 1, sizeof(char)); + char *revDup; + int j = 0; + + for (int i = 0; s[i]; i++) + { + if (isalnum(s[i])) + { + alnumDup[j] = tolower(s[i]); + j++; + } + } + revDup = calloc(strlen(alnumDup) + 1, sizeof(char)); + j = 0; + for (int i = strlen(alnumDup); i; i--) + revDup[j++] = alnumDup[i - 1]; + if (strcmp(alnumDup, revDup)) + { + free(alnumDup); + free(revDup); + return (false); + } + else + { + free(alnumDup); + free(revDup); + return (true); + } +} From a8796b34e8d3e1f80cc141ff1448e7df476f3b3c Mon Sep 17 00:00:00 2001 From: mike2ox Date: Wed, 11 Dec 2024 19:10:06 +0900 Subject: [PATCH 197/396] refactor: Improve space complexity --- house-robber/mike2ox.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/house-robber/mike2ox.ts b/house-robber/mike2ox.ts index ee95f4c3d..d75abae4d 100644 --- a/house-robber/mike2ox.ts +++ b/house-robber/mike2ox.ts @@ -11,14 +11,15 @@ function rob(nums: number[]): number { if (nums.length === 1) return nums[0]; if (nums.length === 2) return Math.max(nums[0], nums[1]); - const dp: number[] = new Array(nums.length); - - dp[0] = nums[0]; - dp[1] = Math.max(nums[0], nums[1]); + let prev = nums[0]; + let maxResult = Math.max(nums[0], nums[1]); + let current = 0; // 남은 집을 순회하면서 최대값을 구함 - for (let i = 2; i < nums.length; i++) - dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]); - - return dp[nums.length - 1]; + for (let i = 2; i < nums.length; i++) { + current = Math.max(maxResult, prev + nums[i]); + prev = maxResult; + maxResult = current; + } + return maxResult; } From 3b86fe84cfb6cdad92b9f0acbc2a95c1c0e1ec88 Mon Sep 17 00:00:00 2001 From: aa601 Date: Wed, 11 Dec 2024 19:24:49 +0900 Subject: [PATCH 198/396] add : solution of the is_palindrome --- valid-palindrome/aa601.c | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 valid-palindrome/aa601.c diff --git a/valid-palindrome/aa601.c b/valid-palindrome/aa601.c new file mode 100644 index 000000000..378261400 --- /dev/null +++ b/valid-palindrome/aa601.c @@ -0,0 +1,27 @@ +bool isPalindrome(char* s) { + int i; + int j; + int size; + char tmp; + int flag; + + i = 0; + size = strlen(s); + j = size - 1; + flag = 1; + while (i < j) { + if (!isalnum(s[i])) { + ++i; + continue ; + } + else if (!isalnum(s[j])) { + --j; + continue ; + } + if (tolower(s[i++]) != tolower(s[j--])) { + flag = 0; + break ; + } + } + return (flag); +} \ No newline at end of file From 345e956b7438a6b48a92dd9d46924ae1ffffa78a Mon Sep 17 00:00:00 2001 From: yeeZinu Date: Wed, 11 Dec 2024 19:26:28 +0900 Subject: [PATCH 199/396] two sum solution --- two-sum/yeeZinu.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 two-sum/yeeZinu.js diff --git a/two-sum/yeeZinu.js b/two-sum/yeeZinu.js new file mode 100644 index 000000000..54c408f7a --- /dev/null +++ b/two-sum/yeeZinu.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} nums + * @param {number} target + * @return {number[]} + */ + +/* +두 수 더하기 +nums: 숫자 배열 +target: 목표 숫자 + +target 숫자에 맞게 nums 배열중 2개를 더함. + return은 더한 두 수의 index + - for i in nums -> target - i 값이 배열내에 있는지 찾기 +*/ +var twoSum = function (nums, target) { + let indexArray = []; // 답을 저장할 배열 + for (let i = 0; i < nums.length; i++) { + let tNum = nums.lastIndexOf(target - nums[i]); // 배열내에 target - nums[i] 찾기 + if (i === tNum) { // 같은 수 사용 방지 + + } + else if (tNum > 0 && indexArray.lastIndexOf(i) === -1) { // 배열내에 원하는 값이 있다면 + indexArray.push(i); + indexArray.push(tNum); + break; + } + } + return indexArray; +}; From 2d6c16477522455a9863b18017cf61d6bc4a7735 Mon Sep 17 00:00:00 2001 From: GangBean Date: Wed, 11 Dec 2024 20:12:06 +0900 Subject: [PATCH 200/396] solve: palindrome-substrings --- palindromic-substrings/GangBean.java | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 palindromic-substrings/GangBean.java diff --git a/palindromic-substrings/GangBean.java b/palindromic-substrings/GangBean.java new file mode 100644 index 000000000..ebb22ac35 --- /dev/null +++ b/palindromic-substrings/GangBean.java @@ -0,0 +1,29 @@ +class Solution { + public int countSubstrings(String s) { + /** + 각 문자를 중간으로 갖는 palindrome 여부 체크 + + 두개의 문자를 중간으로 갖는 palindrome 여부 체크 + */ + int count = 0; + int length = s.length(); + for (int i = 0; i < length; i++) { // O(N) + int start = i; + int end = i; + while (0 <= start && end < length && start <= end && s.charAt(start) == s.charAt(end)) { // O(N) + count++; + start--; + end++; + } + + start = i; + end = i + 1; + while (0 <= start && end < length && start <= end && s.charAt(start) == s.charAt(end)) { // O(N) + count++; + start--; + end++; + } + } + + return count; // O(N^2) + } +} From 763bf3658974d2d49f6dd6f3c8204fbd8f6b8ec6 Mon Sep 17 00:00:00 2001 From: mmyeon Date: Wed, 11 Dec 2024 20:52:22 +0900 Subject: [PATCH 201/396] add solution : 125. Valid Palindrome --- valid-palindrome/mmyeon.js | 45 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 valid-palindrome/mmyeon.js diff --git a/valid-palindrome/mmyeon.js b/valid-palindrome/mmyeon.js new file mode 100644 index 000000000..857ef635f --- /dev/null +++ b/valid-palindrome/mmyeon.js @@ -0,0 +1,45 @@ +/** + * + * 접근 방법 : + * - 문자열 순회하면서 소문자로 변경한 뒤, 정규식을 이용해 알파벳과 숫자만 추출 + * - 추출된 문자에 투 포인터 사용해서 앞뒤 문자 같은지 비교. + * - 다르면 false 바로 리턴하고, 끝까지 같으면 true 반환 + * + * 시간복잡도 : + * - 문자열 길이가 n일 때, O(n) + * - match로 문자열 체크 : O(n) + * - 투 포인터로 앞뒤 문자 비교 : O(n) + * + * 공간복잡도 : + * - 최악의 경우 모든 문자가 알파벳이거나 숫자인 경우 길이가 n이 됨 : O(n) + * + * 배운 점 : + * - 문자값 필요한 게 아니니까 불필요한 배열 변환(reverse) 줄이기 + * - 문자열이 조건 범위에 부합하는지 체크할 때는 정규식 활용하기 + */ + +/** + * @param {string} s + * @return {boolean} + */ + +var isPalindrome = function (s) { + const alphanumericCharacters = s.toLowerCase().match(/[a-z0-9]/g) || []; + + let leftPointer = 0; + let rightPointer = alphanumericCharacters.length - 1; + + while (leftPointer < rightPointer) { + if ( + alphanumericCharacters[leftPointer] !== + alphanumericCharacters[rightPointer] + ) { + return false; + } + + leftPointer++; + rightPointer--; + } + + return true; +}; From ab7172ac25a483ce95790dab980d3314edf8c3d4 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Wed, 11 Dec 2024 21:49:18 +0900 Subject: [PATCH 202/396] :art: Valid Palindrome Solution --- valid-palindrome/dalpang81.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 valid-palindrome/dalpang81.java diff --git a/valid-palindrome/dalpang81.java b/valid-palindrome/dalpang81.java new file mode 100644 index 000000000..b373a1e07 --- /dev/null +++ b/valid-palindrome/dalpang81.java @@ -0,0 +1,12 @@ +class Solution { + public boolean isPalindrome(String s) { + s = s.toLowerCase().trim(); + s = s.replaceAll("[^a-z0-9]", ""); + + StringBuffer sb = new StringBuffer(s); + String reverse = sb.reverse().toString(); + + return(s.equals(reverse)); + + } +} \ No newline at end of file From f3abb58ab27ace1002b87e4e546b769806b5f647 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Wed, 11 Dec 2024 21:52:46 +0900 Subject: [PATCH 203/396] :bug: add newLine --- valid-palindrome/dalpang81.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/valid-palindrome/dalpang81.java b/valid-palindrome/dalpang81.java index b373a1e07..465a3219a 100644 --- a/valid-palindrome/dalpang81.java +++ b/valid-palindrome/dalpang81.java @@ -9,4 +9,4 @@ public boolean isPalindrome(String s) { return(s.equals(reverse)); } -} \ No newline at end of file +} From 833cfcf879d60244ad672fc313899c0cc3ecccf1 Mon Sep 17 00:00:00 2001 From: yeeZinu Date: Wed, 11 Dec 2024 22:21:21 +0900 Subject: [PATCH 204/396] contains duplicate solution --- contains-duplicate/yeeZinu.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 contains-duplicate/yeeZinu.js diff --git a/contains-duplicate/yeeZinu.js b/contains-duplicate/yeeZinu.js new file mode 100644 index 000000000..4c712b90d --- /dev/null +++ b/contains-duplicate/yeeZinu.js @@ -0,0 +1,15 @@ +/** + * @param {number[]} nums + * @return {boolean} + + nums 배열내의 아무 정수나 2개 이상 중복되면 true를 반복하는 함수. + + 시간 복잡도: O(n) + */ +var containsDuplicate = function (nums) { + return nums.length !== new Set(nums).size +} + +console.log(containsDuplicate([1, 2, 3, 1])); // true +// console.log(containsDuplicate([1, 2, 3, 4])); // false +// console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); // true \ No newline at end of file From d9d6dbcc201757e71f5143c388b7aebe3f9c6c8d Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Wed, 11 Dec 2024 22:58:31 +0900 Subject: [PATCH 205/396] :bug: top-k-frequent-elements Solution --- top-k-frequent-elements/dalpang81.java | 30 ++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 top-k-frequent-elements/dalpang81.java diff --git a/top-k-frequent-elements/dalpang81.java b/top-k-frequent-elements/dalpang81.java new file mode 100644 index 000000000..119626f92 --- /dev/null +++ b/top-k-frequent-elements/dalpang81.java @@ -0,0 +1,30 @@ +import java.util.*; +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map map = new HashMap<>(); + + + for(int i : nums) { + map.put(i, map.getOrDefault(i,0) + 1); + } + + PriorityQueue> pq = + new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue)); + + for (Map.Entry entry : map.entrySet()) { + pq.offer(entry); + if (pq.size() > k) { + pq.poll(); // Remove the least frequent element + } + } + + // Step 3: Extract the elements from the heap + int[] result = new int[k]; + for (int i = k - 1; i >= 0; i--) { + result[i] = pq.poll().getKey(); + } + + return result; + + } +} From 00585cd6c76b55e1413373ce92f0364e1cad9aee Mon Sep 17 00:00:00 2001 From: limlim Date: Wed, 11 Dec 2024 23:09:37 +0900 Subject: [PATCH 206/396] longest consecutive sequence solution --- longest-consecutive-sequence/limlimjo.js | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 longest-consecutive-sequence/limlimjo.js diff --git a/longest-consecutive-sequence/limlimjo.js b/longest-consecutive-sequence/limlimjo.js new file mode 100644 index 000000000..e69de29bb From eae9bb06c5501849a34c1ca9259d6aaefe2f6943 Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Wed, 11 Dec 2024 23:47:28 +0900 Subject: [PATCH 207/396] contains-duplicate --- contains-duplicate/taewanseoul.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 contains-duplicate/taewanseoul.ts diff --git a/contains-duplicate/taewanseoul.ts b/contains-duplicate/taewanseoul.ts new file mode 100644 index 000000000..97233136c --- /dev/null +++ b/contains-duplicate/taewanseoul.ts @@ -0,0 +1,14 @@ +/** + * 217. Contains Duplicate + * Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. + * https://leetcode.com/problems/contains-duplicate/description/ + */ +function containsDuplicate(nums: number[]): boolean { + const isDuped = new Set(nums).size !== nums.length; + + return isDuped ? true : false; +} + +// TC: O(n) +// https://262.ecma-international.org/15.0/index.html#sec-get-set.prototype.size +// Set objects must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structure used in this specification is only intended to describe the required observable semantics of Set objects. It is not intended to be a viable implementation model. From 5406dafd5a3c578b034d049c0f8fb12cb9e7068e Mon Sep 17 00:00:00 2001 From: TotschKa Date: Thu, 12 Dec 2024 00:01:15 +0900 Subject: [PATCH 208/396] longest consecutive sequence --- longest-consecutive-sequence/Totschka.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 longest-consecutive-sequence/Totschka.ts diff --git a/longest-consecutive-sequence/Totschka.ts b/longest-consecutive-sequence/Totschka.ts new file mode 100644 index 000000000..0061ed72a --- /dev/null +++ b/longest-consecutive-sequence/Totschka.ts @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/longest-consecutive-sequence/ +function longestConsecutive(nums: number[]): number { + if (nums.length === 0) { + return 0; + } + nums = [...new Set(nums)].sort((a, b) => a - b); + let ans = 0; + let left = 0, right = 1; + for (let i = 0; i < nums.length; i++) { + if (nums[i] + 1 === nums[i + 1]) { + ans = Math.max(ans, right - left); + } else { + left = right; + } + right++; + } + return ans + 1; +} From 55986a055f4bc506490ea44bc67911f345563413 Mon Sep 17 00:00:00 2001 From: siroo Date: Thu, 12 Dec 2024 02:53:46 +0900 Subject: [PATCH 209/396] House Robber solution --- house-robber/jungsiroo.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 house-robber/jungsiroo.py diff --git a/house-robber/jungsiroo.py b/house-robber/jungsiroo.py new file mode 100644 index 000000000..c985c32db --- /dev/null +++ b/house-robber/jungsiroo.py @@ -0,0 +1,38 @@ +class Solution: + def bfs(self, nums): + from collections import deque + queue = deque() + + # price, idx, robbed prev + queue.append([0, 0, False]) + queue.append([0, 0, True]) + ret = 0 + + while queue: + price, idx, prev = queue.popleft() + ret = max(ret, price) + if idx == len(nums): + continue + + if prev: + queue.append([price, idx+1, False]) + else: + queue.append([price, idx+1, False]) + queue.append([price+nums[idx], idx+1, True]) + + return ret + + def rob(self, nums: List[int]) -> int: + # BFS - Slow and out of memory + """return self.bfs(nums)""" + + # DP + n = len(nums) + record = [[0]*n for _ in range(2)] + record[1][0] = nums[0] + + for i in range(1, n): + record[1][i] = max(record[0][i-1]+nums[i], record[1][i]) + record[0][i] = max(record[1][i-1], record[0][i-1]) + + return max(record[1][-1], record[0][-1]) From 107c885ba151a0bcc09bced0fa54caca6750c558 Mon Sep 17 00:00:00 2001 From: siroo Date: Thu, 12 Dec 2024 03:29:10 +0900 Subject: [PATCH 210/396] House Robber solution fix --- house-robber/jungsiroo.py | 1 + 1 file changed, 1 insertion(+) diff --git a/house-robber/jungsiroo.py b/house-robber/jungsiroo.py index c985c32db..ac721cab7 100644 --- a/house-robber/jungsiroo.py +++ b/house-robber/jungsiroo.py @@ -36,3 +36,4 @@ def rob(self, nums: List[int]) -> int: record[0][i] = max(record[1][i-1], record[0][i-1]) return max(record[1][-1], record[0][-1]) + From d1fbcfb2dc0b6651b1f19b6ea173a5a0da456bae Mon Sep 17 00:00:00 2001 From: suhacs Date: Wed, 11 Dec 2024 16:25:33 -0500 Subject: [PATCH 211/396] contains duplicate --- contains-duplicate/suhacs.js | 19 +------------------ 1 file changed, 1 insertion(+), 18 deletions(-) diff --git a/contains-duplicate/suhacs.js b/contains-duplicate/suhacs.js index 75481ee49..f018c8820 100644 --- a/contains-duplicate/suhacs.js +++ b/contains-duplicate/suhacs.js @@ -1,24 +1,7 @@ -/** - * @description - * time complexity: O(n) - * space complexity: O(n) - * approach/strategy: - * 1. brute force + hash table - */ - -/** - * @param {number[]} nums - * @return {boolean} - */ - function containsDuplicate(nums) { const setLength = [...new Set(nums)].length; const numLength = nums.length; - - if (numLength === setLength) return false; - else return true; + return numLength === setLength ? false : true; } - console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); - // From 063cbd4e1bee05494751c7bbe68c695695902ff7 Mon Sep 17 00:00:00 2001 From: Paik Date: Thu, 12 Dec 2024 07:59:54 +0900 Subject: [PATCH 212/396] feat: 198. House Robber --- house-robber/gwbaik9717.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 house-robber/gwbaik9717.js diff --git a/house-robber/gwbaik9717.js b/house-robber/gwbaik9717.js new file mode 100644 index 000000000..e54c9c2e9 --- /dev/null +++ b/house-robber/gwbaik9717.js @@ -0,0 +1,18 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function (nums) { + const n = nums.length; + const dp = Array.from({ length: n + 1 }, () => 0); + dp[1] = nums[0]; + + for (let i = 2; i < n + 1; i++) { + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]); + } + + return dp.at(-1); +}; From a094799582ccd94f2cb227d4ef1cfbbda44c7889 Mon Sep 17 00:00:00 2001 From: Yoon Kim Date: Wed, 11 Dec 2024 15:33:50 -0800 Subject: [PATCH 213/396] top k frequent elements solution --- top-k-frequent-elements/yoonthecoder.js | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 top-k-frequent-elements/yoonthecoder.js diff --git a/top-k-frequent-elements/yoonthecoder.js b/top-k-frequent-elements/yoonthecoder.js new file mode 100644 index 000000000..2d297c646 --- /dev/null +++ b/top-k-frequent-elements/yoonthecoder.js @@ -0,0 +1,25 @@ +var topKFrequent = function (nums, k) { + // 1. count the frequency of each number in the array + const map = new Map(); + + // iterating through the array to count how many times each num appears. + for (const num of nums) { + // if the num already exists in the map, increment its count + if (map.has(num)) { + map.set(num, map.get(num) + 1); + } // otherwise, set it to 1 + else map.set(num, 1); + } + + // 2.create an array to store the freqeuncy numbers + const freqArr = []; + for (const [num, freq] of map) { + freqArr.push([num, freq]); + } + // sort in descending order by frequency + freqArr.sort((a, b) => b[1] - a[1]); + return freqArr.slice(0, k).map(([num]) => num); +}; + +// Time complexity: O(nlogn) +// Space complexity: O(n) From 5fcd5824041a92d4d9d987c7fc28a1d36fc2540c Mon Sep 17 00:00:00 2001 From: easyone Date: Thu, 12 Dec 2024 10:06:24 +0900 Subject: [PATCH 214/396] Feat: Add solution of longest-consecutive-sequence. --- longest-consecutive-sequence/easyone-jwlee.go | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 longest-consecutive-sequence/easyone-jwlee.go diff --git a/longest-consecutive-sequence/easyone-jwlee.go b/longest-consecutive-sequence/easyone-jwlee.go new file mode 100644 index 000000000..87cd429fd --- /dev/null +++ b/longest-consecutive-sequence/easyone-jwlee.go @@ -0,0 +1,40 @@ +// 풀이 +// You must write an algorithm that runs in O(n) time. +// TC를 O(n) 이내로 해야한다는 것은 sort를 쓰지 말라는 의미. +// map을 사용하고 순회하며 연속이 시작되는 값을 찾고 찾으면 연속되는지 찾기. + +// TC +// 순회하는 map안에서 for문을 또 호출하긴 하지만, +// 모든 값이 연속되는 값이라고 했을 때 +// 연속이 시작되는 값 외에는 한 번씩 바로 지나가게 되고(n*1), 시작되는 값부터 연속이 끝나는 시점까지 n번이라(1*n) +// O(n+n) 이기 때문에 TC는 O(n) + +// SC +// map이 최대로 차지하는 공간은 O(n) + +func longestConsecutive(nums []int) int { + m := make(map[int]bool) + for _, num := range nums { + m[num] = true + } + length := 1 + maxLength := 0 + for k := range m { + if _, ok := m[k-1]; !ok { + i := 1 + for { + if _, ok := m[k+i]; ok { + length++ + i++ + } else { + break + } + } + if maxLength < length { + maxLength = length + } + length = 1 + } + } + return maxLength +} From ed398ffb22e91868c5471528c5c6c8d947b6dc3d Mon Sep 17 00:00:00 2001 From: easyone Date: Thu, 12 Dec 2024 10:06:42 +0900 Subject: [PATCH 215/396] Docs: Add comments explaining the solution process. --- contains-duplicate/easyone-jwlee.go | 14 ++++++++++++++ top-k-frequent-elements/easyone-jwlee.go | 11 +++++++++++ valid-palindrome/easyone-jwlee.go | 11 +++++++++++ 3 files changed, 36 insertions(+) diff --git a/contains-duplicate/easyone-jwlee.go b/contains-duplicate/easyone-jwlee.go index 692163447..1dafb7676 100644 --- a/contains-duplicate/easyone-jwlee.go +++ b/contains-duplicate/easyone-jwlee.go @@ -1,3 +1,17 @@ +// 풀이 +// map으로 중복된 값이 있는지 체크 + +// TC +// 중복이 하나도 없는 경우에 최대 n번 조회 +// n번 반복시 총 작업의 복잡도는 O(n) + +// SC +// n개의 숫자를 저장하면 map이 사용하는 공간은 최대 O(n) + +// (+) 정렬을 사용한다면? +// 입력된 배열을 정렬해서 서로 인접한 값을 비교하면 O(1)의 SC로 중복 확인 가능. +// 그러나 정렬을 사용하면 TC가 O(nlogn). + func containsDuplicate(nums []int) bool { m := make(map[int]int) for _, num := range nums { diff --git a/top-k-frequent-elements/easyone-jwlee.go b/top-k-frequent-elements/easyone-jwlee.go index 5a024515b..f5340e23f 100644 --- a/top-k-frequent-elements/easyone-jwlee.go +++ b/top-k-frequent-elements/easyone-jwlee.go @@ -1,3 +1,14 @@ +// 풀이 +// map으로 입력 숫자들이 각각 몇번 반복되는지 정리 +// [][]int를 선언하고 반복된 횟수를 index로, 입력 숫자값을 배열에 append한다. +// 그리고 배열을 역순으로 순회하며 k개의 element를 가진 결과 배열을 만든다. + +// TC +// O(n) + +// SC +// 모든 숫자가 다르다고 해도 각 숫자는 하나의 하위배열에만 속한다. 따라서 O(n) + func topKFrequent(nums []int, k int) []int { m := make(map[int]int) for _, num := range nums { diff --git a/valid-palindrome/easyone-jwlee.go b/valid-palindrome/easyone-jwlee.go index 8b344942a..dfa001a88 100644 --- a/valid-palindrome/easyone-jwlee.go +++ b/valid-palindrome/easyone-jwlee.go @@ -1,3 +1,14 @@ +// 풀이 +// 유효한 string 값만 정제하고 palindrome check. + +// TC +// 입력된 string의 길이에 따라 최대 O(n) + +// SC +// validStr으로 유효한 string을 정제하기 때문에 최대 O(n) + +// (+) 입력된 string을 사용하는 방식으로 개선하면 SC가 O(1) + func isPalindrome(s string) bool { s = strings.ToLower(s) validStr := "" From 499d34ab24968da2d6f60d7f2376a4f4beafe063 Mon Sep 17 00:00:00 2001 From: ChangHyun Lee <34360681+heypaprika@users.noreply.github.com> Date: Thu, 12 Dec 2024 10:33:02 +0900 Subject: [PATCH 216/396] Update valid-palindrome/heypaprika.py Co-authored-by: moonhyeok song --- valid-palindrome/heypaprika.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/valid-palindrome/heypaprika.py b/valid-palindrome/heypaprika.py index 58463d55f..64b03e9bd 100644 --- a/valid-palindrome/heypaprika.py +++ b/valid-palindrome/heypaprika.py @@ -7,9 +7,7 @@ def isPalindrome(self, s: str) -> bool: if (ord("a") <= ord(item) <= ord("z")) or (ord("0") <= ord(item) <= ord("9")): new_s += item output = True - for i in range(len(new_s) // 2): - if new_s[i] != new_s[-i-1]: - output = False - break + new_s_2 = new_s[::-1] + return new_s_2 == new_s return output From fb3980df3abef3d81ed2dd61ebe788dc6b83b3c2 Mon Sep 17 00:00:00 2001 From: Changhyun Lee Date: Thu, 12 Dec 2024 10:36:04 +0900 Subject: [PATCH 217/396] EDIT : contains-duplicate Big-O prediction --- contains-duplicate/heypaprika.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/heypaprika.py b/contains-duplicate/heypaprika.py index dfa6d3123..e2dd01bc8 100644 --- a/contains-duplicate/heypaprika.py +++ b/contains-duplicate/heypaprika.py @@ -1,4 +1,4 @@ -# Big-O 예상 : O(n*k) +# Big-O 예상 : O(n) class Solution: def containsDuplicate(self, nums: List[int]) -> bool: num_dict = {} From de3351dabd354aa6e32cb369cde2b2cc71ce3107 Mon Sep 17 00:00:00 2001 From: pmjuu Date: Wed, 11 Dec 2024 21:21:04 -0500 Subject: [PATCH 218/396] feat: solve house-robber --- house-robber/pmjuu.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 house-robber/pmjuu.py diff --git a/house-robber/pmjuu.py b/house-robber/pmjuu.py new file mode 100644 index 000000000..0f8df0ac7 --- /dev/null +++ b/house-robber/pmjuu.py @@ -0,0 +1,16 @@ +from typing import List + +class Solution: + def rob(self, nums: List[int]) -> int: + if len(nums) == 1: + return nums[0] + + # prev1: 이전 집까지의 최대 이익 + # prev2: 전전 집까지의 최대 이익 + prev1, prev2 = 0, 0 + for num in nums: + temp = prev1 + prev1 = max(prev2 + num, prev1) # 현재 집을 털었을 때와 안 털었을 때 중 더 큰 이익 선택 + prev2 = temp + + return prev1 From f7ae499159a10c2fb5e55295b6ab0d6a379f5d27 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Thu, 12 Dec 2024 14:02:11 +0900 Subject: [PATCH 219/396] Solved 128. Longest Consecutive Sequence problem --- longest-consecutive-sequence/KwonNayeon.py | 38 ++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 longest-consecutive-sequence/KwonNayeon.py diff --git a/longest-consecutive-sequence/KwonNayeon.py b/longest-consecutive-sequence/KwonNayeon.py new file mode 100644 index 000000000..ea15875f8 --- /dev/null +++ b/longest-consecutive-sequence/KwonNayeon.py @@ -0,0 +1,38 @@ +""" +Title: 128. Longest Consecutive Sequence +Link: https://leetcode.com/problems/longest-consecutive-sequence/ + +Question: + - Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. + - You must write an algorithm that runs in O(n) time. + +Constraints: + - 0 <= nums.length <= 10^5 + - -10^9 <= nums[i] <= 10^9 + +Time Complexity: + - O(n log n) +Space Complexity: + - O(n) + +Notes: + - sorted(nums)를 사용하면 TC가 O(n log n)이 되어 문제의 조건을 충족하지 못하지만, 이 방법이 제가 생각해서 풀 수 있는 최선이라 일단 이대로 제출합니다! 다른 분들 답안 참고하여 다시 풀어보겠습니다 :) +""" + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + nums = sorted(nums) + max_length = 0 + current_length = 1 + + for i in range(1, len(nums)): + if nums[i] == nums[i-1] + 1: + current_length += 1 + elif nums[i] == nums[i-1]: + continue + else: + max_length = max(max_length, current_length) + current_length = 1 + + max_length = max(max_length, current_length) + return max_length From 65c2c59f447f3aea0d9889046e161672b57afcef Mon Sep 17 00:00:00 2001 From: Nayeon Date: Thu, 12 Dec 2024 15:29:35 +0900 Subject: [PATCH 220/396] Solved 198. House Robber using Python code --- house-robber/KwonNayeon.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 house-robber/KwonNayeon.py diff --git a/house-robber/KwonNayeon.py b/house-robber/KwonNayeon.py new file mode 100644 index 000000000..600128dcb --- /dev/null +++ b/house-robber/KwonNayeon.py @@ -0,0 +1,28 @@ +""" +Title: 198. House Robber + +Constraints: + - 1 <= nums.length <= 100 + - 0 <= nums[i] <= 400 + +Time Complexity: + - O(n) +Space Complexity: + - O(n) +""" + +class Solution: + def rob(self, nums: List[int]) -> int: + + if len(nums) == 1: + return nums[0] + elif len(nums) == 2: + return max(nums[0], nums[1]) + + dp = [0]*len(nums) + dp[0] = nums[0] + dp[1] = max(nums[0], nums[1]) + + for i in range(2, len(nums)): + dp[i] = max(dp[i-1], nums[i] + dp[i-2]) + return dp[-1] From 7816391328929fee32b9f84713d7b7cb2153510a Mon Sep 17 00:00:00 2001 From: yeeZinu Date: Thu, 12 Dec 2024 15:44:46 +0900 Subject: [PATCH 221/396] =?UTF-8?q?=20cl=20=EA=B0=9C=ED=96=89=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/yeeZinu.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/yeeZinu.js b/contains-duplicate/yeeZinu.js index 4c712b90d..b2e481a1d 100644 --- a/contains-duplicate/yeeZinu.js +++ b/contains-duplicate/yeeZinu.js @@ -12,4 +12,4 @@ var containsDuplicate = function (nums) { console.log(containsDuplicate([1, 2, 3, 1])); // true // console.log(containsDuplicate([1, 2, 3, 4])); // false -// console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); // true \ No newline at end of file +// console.log(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2])); // true From a5e4185bcdb01d02648a78c5a6f61a51e3843903 Mon Sep 17 00:00:00 2001 From: yeeZinu Date: Thu, 12 Dec 2024 17:18:22 +0900 Subject: [PATCH 222/396] valid parentheses solve --- valid-parentheses/yeeZinu.js | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 valid-parentheses/yeeZinu.js diff --git a/valid-parentheses/yeeZinu.js b/valid-parentheses/yeeZinu.js new file mode 100644 index 000000000..1516d5d7b --- /dev/null +++ b/valid-parentheses/yeeZinu.js @@ -0,0 +1,43 @@ +/** + * @param {string} s + * @return {boolean} + + 괄호 유효성 검사( + 어느 괄호로 열어도 상관은 없지만 열었으면 닫아야지 true 안닫으면 false + ({)} -> 이런식으로 중간에 섞여서 닫혀있지 않다는 전제의 문제 + */ +var isValid = function (s) { + if (s.length % 2 === 1) { + return false + } + + // 괄호들이 들어갈 스택배열 + const stack = []; + + // 괄호 짝 객체 + const pair = { + "(": ")", + "{": "}", + "[": "]", + } + + for (let i = 0; i < s.length; i++) { + // 열린괄호면 스택추가 + if (s[i] in pair) { + stack.push(s[i]); + } + // 닫힌 괄호라면? + else { + // 스택배열의 마지막이 같은 종류의 괄호라면 제거 + if (pair[stack.at(-1)] === s[i]) { + stack.pop(); + } + // 아니면 false + else { + return false + } + } + } + // 스택배열이 비었으면 true + return stack.length === 0; +}; From 42e2dd242710b034f158fb947e5012751d5e028a Mon Sep 17 00:00:00 2001 From: Yoon Kim Date: Thu, 12 Dec 2024 01:33:27 -0800 Subject: [PATCH 223/396] longest consecutive sequence solution --- longest-consecutive-sequence/yoonthecoder.js | 21 ++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 longest-consecutive-sequence/yoonthecoder.js diff --git a/longest-consecutive-sequence/yoonthecoder.js b/longest-consecutive-sequence/yoonthecoder.js new file mode 100644 index 000000000..5c9e71256 --- /dev/null +++ b/longest-consecutive-sequence/yoonthecoder.js @@ -0,0 +1,21 @@ +var longestConsecutive = function (nums) { + // remove the duplicates from the array and sort it in an ascending order. + const setArray = [...new Set(nums)]; + const sortedArray = setArray.sort((a, b) => a - b); + // create a set to store streak lengths, even when count resets. + const countSet = new Set(); + let count = 0; + for (let i = 0; i < sortedArray.length; i++) { + if (sortedArray[i] + 1 == sortedArray[i + 1]) { + count += 1; + countSet.add(count); + } else { + count = 0; + } + } + + return nums.length === 0 ? 0 : countSet.size + 1; +}; + +// Time complexity: O(nlogn) => TODO: need to improve this to O(n) +// Space complexity: O(n) From 0a0bab92fd032af1d1a01892e5a20e052fe1cc27 Mon Sep 17 00:00:00 2001 From: limlim Date: Thu, 12 Dec 2024 19:02:48 +0900 Subject: [PATCH 224/396] longest consecutive sequence solution --- longest-consecutive-sequence/limlimjo.js | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/longest-consecutive-sequence/limlimjo.js b/longest-consecutive-sequence/limlimjo.js index e69de29bb..3ff7f8d2f 100644 --- a/longest-consecutive-sequence/limlimjo.js +++ b/longest-consecutive-sequence/limlimjo.js @@ -0,0 +1,35 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function(nums) { + // 첫 번째 정렬을 한다. + if (nums.length === 0) { + return 0; + } + + nums.sort((a, b) => a - b); // 오름차순으로 정렬 + console.log(nums); + + // 두 번째 숫자가 1씩 계속해서 증가하는 구간을 찾는다. + let longest = 0; + let length = 1; + + for (let i=0; i Date: Thu, 12 Dec 2024 19:18:59 +0900 Subject: [PATCH 225/396] top k frequent elements solution --- top-k-frequent-elements/yeeZinu.js | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 top-k-frequent-elements/yeeZinu.js diff --git a/top-k-frequent-elements/yeeZinu.js b/top-k-frequent-elements/yeeZinu.js new file mode 100644 index 000000000..c783f47e8 --- /dev/null +++ b/top-k-frequent-elements/yeeZinu.js @@ -0,0 +1,31 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + * + * nums 배열 내 최빈도 숫자 k개 출력 + * + */ +var topKFrequent = function (nums, k) { + // 빈도 체크할 객체 + let frequent = {}; + + for (let i = 0; i < nums.length; i++) { + // 숫자 중복될때마다 +1 + if (frequent[nums[i]] > 0) { + frequent[nums[i]]++; + } + // 없으면 1로 초기화 + else { + frequent[nums[i]] = 1; + } + } + + // 정렬을 위해 entries를 사용해 배열로 변환 + const frequentEntries = Object.entries(frequent); + frequentEntries.sort((a, b) => b[1] - a[1]); // 내림차순 정렬 + + // k갯수만큼 배열 자르기 및 배열 내부 값 number로 변경 + const topK = frequentEntries.slice(0, k).map((i) => Number(i[0])); + return topK; +}; From ddca66ddc2a6d414ad739f3cae5294fdf317ba7c Mon Sep 17 00:00:00 2001 From: anniemon Date: Mon, 9 Dec 2024 17:01:06 +0900 Subject: [PATCH 226/396] feat: contains duplicate --- contains-duplicate/anniemon.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 contains-duplicate/anniemon.js diff --git a/contains-duplicate/anniemon.js b/contains-duplicate/anniemon.js new file mode 100644 index 000000000..d7c02154b --- /dev/null +++ b/contains-duplicate/anniemon.js @@ -0,0 +1,23 @@ +/** + * 시간 복잡도: + * 맵에서 nums[i]를 찾거나 삽입하는 데 걸리는 시간 O(1) * n(nums.length) + * 즉, O(n) + * 공간 복잡도: + * 최대 map의 크기는 nums.length만큼 + * 즉, O(n) + */ +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function(nums) { + const map = new Map(); + for(let i = 0; i < nums.length; i++) { + if(!map.has(nums[i])) { + map.set(nums[i], i); + } else { + return true; + } + } + return false; +}; From 2d72388576d113ebae006db1606577a7a10dddda Mon Sep 17 00:00:00 2001 From: anniemon Date: Mon, 9 Dec 2024 17:01:59 +0900 Subject: [PATCH 227/396] feat: top k frequent elements --- top-k-frequent-elements/anniemon.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 top-k-frequent-elements/anniemon.js diff --git a/top-k-frequent-elements/anniemon.js b/top-k-frequent-elements/anniemon.js new file mode 100644 index 000000000..5192f7509 --- /dev/null +++ b/top-k-frequent-elements/anniemon.js @@ -0,0 +1,24 @@ +/** + * 시간 복잡도: + * nums.length만큼의 배열을 정렬해야 하므로 + * 즉, O(n * log n) + * 공간 복잡도: + * 최대 nums.length만큼의 map 생성 + * 즉, O(n) + */ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function(nums, k) { + const map = new Map(); + for(const n of nums) { + if(!map.has(n)) { + map.set(n, 0); + } + map.set(n, map.get(n) + 1) + } + const sorted = Array.from(map).sort((a, b) => b[1]-a[1]); + return sorted.slice(0, k).map(e => e[0]) +}; From d0956f1cd5bce3b30e24b3d35e24270c9bdd39c0 Mon Sep 17 00:00:00 2001 From: anniemon Date: Mon, 9 Dec 2024 17:02:14 +0900 Subject: [PATCH 228/396] feat: valid palindrome --- valid-palindrome/anniemon.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 valid-palindrome/anniemon.js diff --git a/valid-palindrome/anniemon.js b/valid-palindrome/anniemon.js new file mode 100644 index 000000000..e4218ac59 --- /dev/null +++ b/valid-palindrome/anniemon.js @@ -0,0 +1,34 @@ +/** + * 시간 복잡도: + * s.length만큼 탐색. 즉, O(n) + * 공간 복잡도: + * 변수와 함수만 저장. 즉, O(1) + */ + +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function(s) { + const isAlphaNumeric = (v) => { + return (/^[a-z0-9]$/i).test(v); + }; + + let l = 0; + let r = s.length - 1; + while(l < r) { + while(!isAlphaNumeric(s[l]) && l < r) { + l++; + } + while(!isAlphaNumeric(s[r]) && l < r) { + r--; + } + + if(s[l].toLowerCase() !== s[r].toLowerCase()) { + return false; + } + l++; + r--; + } + return true; +}; From de9ff875f8bd1bfc541110cd727d7b9d6efb532f Mon Sep 17 00:00:00 2001 From: anniemon Date: Thu, 12 Dec 2024 18:44:27 +0900 Subject: [PATCH 229/396] feat: longest consecutive sequence --- longest-consecutive-sequence/anniemon.js | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 longest-consecutive-sequence/anniemon.js diff --git a/longest-consecutive-sequence/anniemon.js b/longest-consecutive-sequence/anniemon.js new file mode 100644 index 000000000..695c091e7 --- /dev/null +++ b/longest-consecutive-sequence/anniemon.js @@ -0,0 +1,30 @@ +/** + * 시간 복잡도: + * set의 요소 중 연속하는 시퀀스의 첫번째 숫자일 때만 + * while 루프를 실행 + * 따라서 요소당 최대 1회 순회 + * 즉, 시간 복잡도는 O(n) + * 공간 복잡도: + * set은 중복이 없을 경우 최대 O(n)를 차지함 + * 즉, 공간 복잡도는 O(n) + */ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + const set = new Set(nums); + let res = 0; + for (const n of set) { + let seqLen = 0, target = n; + const isSeqStart = !set.has(target - 1); + if (isSeqStart) { + while (set.has(target)) { + target++; + seqLen++; + } + } + res = Math.max(seqLen, res); + } + return res; +}; From ff2f60586ddb335ce908055928948d5cd8398424 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Thu, 12 Dec 2024 20:26:02 +0900 Subject: [PATCH 230/396] :art: Longest Consecutive Sequence Solution --- longest-consecutive-sequence/dalpang81.java | 32 +++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 longest-consecutive-sequence/dalpang81.java diff --git a/longest-consecutive-sequence/dalpang81.java b/longest-consecutive-sequence/dalpang81.java new file mode 100644 index 000000000..5ef58b501 --- /dev/null +++ b/longest-consecutive-sequence/dalpang81.java @@ -0,0 +1,32 @@ +import java.util.*; + +class Solution { + public int longestConsecutive(int[] nums) { + Set numSet = new HashSet<>(); + for (int num : nums) { + numSet.add(num); + } + + int longNum = 0; + + // 각 숫자에 대해 시퀀스 시작 여부를 확인 + for (int num : numSet) { + // num-1이 없는 경우에만 시퀀스를 시작 + if (!numSet.contains(num - 1)) { + int currentNum = num; + int currentLong = 1; + + // 연속된 숫자를 탐색 + while (numSet.contains(currentNum + 1)) { + currentNum++; + currentLong++; + } + + // 가장 긴 시퀀스를 갱신 + longNum = Math.max(longNum, currentLong); + } + } + + return longNum; + } +} From 27d89c9791447cb49f5e654f5ab5c6f4c4d9606d Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Thu, 12 Dec 2024 20:56:50 +0900 Subject: [PATCH 231/396] feat: Longest Consecutive Sequence #240 --- longest-consecutive-sequence/donghyeon95.java | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 longest-consecutive-sequence/donghyeon95.java diff --git a/longest-consecutive-sequence/donghyeon95.java b/longest-consecutive-sequence/donghyeon95.java new file mode 100644 index 000000000..659a9a992 --- /dev/null +++ b/longest-consecutive-sequence/donghyeon95.java @@ -0,0 +1,34 @@ +import java.util.HashSet; + +public class Solution { + public int longestConsecutive(int[] nums) { + HashSet set = new HashSet<>(); + for (int num : nums) { + set.add(num); + } + + int maxStreak = 0; + + for (int num : nums) { + // 내가 시작 값이라면 + if (!set.contains(num - 1)) { + int currentNum = num; + int currentStreak = 1; + + // 나로부터 연결되는 값을 찾는다. + while (set.contains(currentNum + 1)) { + currentNum++; + currentStreak++; + } + + maxStreak = Math.max(maxStreak, currentStreak); + } + } + + return maxStreak; + } +} + + + + From d68a21ddeba10bb2e75e65fbd61a2de63a5cc9aa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=81=EC=9E=AC?= Date: Thu, 12 Dec 2024 21:04:33 +0900 Subject: [PATCH 232/396] add: solve #198 House Robber with ts --- house-robber/YJason-K.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 house-robber/YJason-K.ts diff --git a/house-robber/YJason-K.ts b/house-robber/YJason-K.ts new file mode 100644 index 000000000..98fe0bbb5 --- /dev/null +++ b/house-robber/YJason-K.ts @@ -0,0 +1,30 @@ +/** + * 주어진 배열에서 인접한 집을 털지 않고 훔칠 수 있는 최대 금액을 계산하는 함수 + * - 시간 복잡도: O(n) + * - 배열을 한 번 순회하면서 최대 금액을 계산 + * - 공간 복잡도: O(1) + * - 추가 배열 없이 변수만 사용하여 공간 효율성을 최적화 + * + * @param {number[]} nums - 각 집에 있는 돈의 양을 나타내는 배열 + * @returns {number} - 경보를 울리지 않고 훔칠 수 있는 최대 금액 + */ +function rob(nums: number[]): number { + if (nums.length === 0) return 0; // 빈 배열 처리 + if (nums.length === 1) return nums[0]; // 집이 한 채만 있는 경우, 그 집의 돈 반환 + + // 1. 변수 초기화: 이전 두 집까지의 최대 금액 + let prev2 = 0; // 두 번째 이전 집까지의 최대 금액 + let prev1 = nums[0]; // 첫 번째 이전 집까지의 최대 금액 + + // 2. 배열 순회: 각 집에서 훔칠 수 있는 최대 금액 계산 + for (let i = 1; i < nums.length; i++) { + // 현재 집까지의 최대 금액은 (현재 집 + prev2) 또는 prev1 중 더 큰 값 + const cur = Math.max(nums[i] + prev2, prev1); + + // 이전 두 집의 최대 금액 업데이트 + prev2 = prev1; + prev1 = cur; + } + + return prev1; // 마지막 집까지의 최대 금액 반환 +} \ No newline at end of file From 54cbbb5c0210fd48bb6d2f1167e45d1acc134db8 Mon Sep 17 00:00:00 2001 From: yeeZinu Date: Thu, 12 Dec 2024 21:07:10 +0900 Subject: [PATCH 233/396] longest consecutive sequence solution --- longest-consecutive-sequence/yeeZinu.js | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 longest-consecutive-sequence/yeeZinu.js diff --git a/longest-consecutive-sequence/yeeZinu.js b/longest-consecutive-sequence/yeeZinu.js new file mode 100644 index 000000000..83b024ac0 --- /dev/null +++ b/longest-consecutive-sequence/yeeZinu.js @@ -0,0 +1,29 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + // set으로 중복된 element 제거 + const numSet = new Set(nums); + // 최대 연속 길이 변수 + let maxLength = 0; + + // 최대 연속 길이 찾기 + for (let num of numSet) { + // 만약 현재 수 -1이 없다면? + if (!numSet.has(num - 1)) { + let currentNum = num; //현재값이 시작 + let currentLength = 1; //최대 길이 1로 초기화 + + // 현재값 +1이 있을 때 까지 반복 + while (numSet.has(currentNum + 1)) { + currentNum++; + currentLength++; + } + + // 최대길이 값과 현재 길이값중 더 높은것이 최대길이값 + maxLength = Math.max(maxLength, currentLength); + } + } + return maxLength; +}; From 5732b2b331ba3b965d1a8077d0ea1370a4d510ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=81=EC=9E=AC?= Date: Thu, 12 Dec 2024 21:04:33 +0900 Subject: [PATCH 234/396] add: solve #264 House Robber with ts --- house-robber/YJason-K.ts | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 house-robber/YJason-K.ts diff --git a/house-robber/YJason-K.ts b/house-robber/YJason-K.ts new file mode 100644 index 000000000..98fe0bbb5 --- /dev/null +++ b/house-robber/YJason-K.ts @@ -0,0 +1,30 @@ +/** + * 주어진 배열에서 인접한 집을 털지 않고 훔칠 수 있는 최대 금액을 계산하는 함수 + * - 시간 복잡도: O(n) + * - 배열을 한 번 순회하면서 최대 금액을 계산 + * - 공간 복잡도: O(1) + * - 추가 배열 없이 변수만 사용하여 공간 효율성을 최적화 + * + * @param {number[]} nums - 각 집에 있는 돈의 양을 나타내는 배열 + * @returns {number} - 경보를 울리지 않고 훔칠 수 있는 최대 금액 + */ +function rob(nums: number[]): number { + if (nums.length === 0) return 0; // 빈 배열 처리 + if (nums.length === 1) return nums[0]; // 집이 한 채만 있는 경우, 그 집의 돈 반환 + + // 1. 변수 초기화: 이전 두 집까지의 최대 금액 + let prev2 = 0; // 두 번째 이전 집까지의 최대 금액 + let prev1 = nums[0]; // 첫 번째 이전 집까지의 최대 금액 + + // 2. 배열 순회: 각 집에서 훔칠 수 있는 최대 금액 계산 + for (let i = 1; i < nums.length; i++) { + // 현재 집까지의 최대 금액은 (현재 집 + prev2) 또는 prev1 중 더 큰 값 + const cur = Math.max(nums[i] + prev2, prev1); + + // 이전 두 집의 최대 금액 업데이트 + prev2 = prev1; + prev1 = cur; + } + + return prev1; // 마지막 집까지의 최대 금액 반환 +} \ No newline at end of file From a774fefd3a2ed0105d176aa379d7506de3956d7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=98=81=EC=9E=AC?= Date: Thu, 12 Dec 2024 21:15:50 +0900 Subject: [PATCH 235/396] fix: add line break --- contains-duplicate/YJason-K.ts | 2 +- house-robber/YJason-K.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contains-duplicate/YJason-K.ts b/contains-duplicate/YJason-K.ts index 4b14b86db..07cdb4f3a 100644 --- a/contains-duplicate/YJason-K.ts +++ b/contains-duplicate/YJason-K.ts @@ -14,4 +14,4 @@ function containsDuplicate(nums: number[]): boolean { } } return false; -}; \ No newline at end of file +}; diff --git a/house-robber/YJason-K.ts b/house-robber/YJason-K.ts index 98fe0bbb5..6a32fdb12 100644 --- a/house-robber/YJason-K.ts +++ b/house-robber/YJason-K.ts @@ -27,4 +27,4 @@ function rob(nums: number[]): number { } return prev1; // 마지막 집까지의 최대 금액 반환 -} \ No newline at end of file +} From de2bbe63a9c6d8ffde2fbb63a8f3f376e80c26a0 Mon Sep 17 00:00:00 2001 From: limlim Date: Thu, 12 Dec 2024 21:33:26 +0900 Subject: [PATCH 236/396] house robber solution --- house-robber/limlimjo.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 house-robber/limlimjo.js diff --git a/house-robber/limlimjo.js b/house-robber/limlimjo.js new file mode 100644 index 000000000..df7098c3f --- /dev/null +++ b/house-robber/limlimjo.js @@ -0,0 +1,22 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + // 1. nums 배열 0일 때와 1일 때 + if (nums.length === 0) return 0; + if (nums.length === 1) return nums[0]; + + // 2. i=1일 때 + nums[1] = Math.max(nums[0], nums[1]); + + // 3. i=2일 때부터 for문 순회 + for (let i=2; i O(n) +// 공간복잡도: nums 배열 그대로 수정하여 계산 -> O(1) From 920f50337a44b5aacecd04b29175347cca3a1d86 Mon Sep 17 00:00:00 2001 From: mmyeon Date: Thu, 12 Dec 2024 21:48:16 +0900 Subject: [PATCH 237/396] add solution : 347. Top K Frequent Elements --- top-k-frequent-elements/mmyeon.js | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 top-k-frequent-elements/mmyeon.js diff --git a/top-k-frequent-elements/mmyeon.js b/top-k-frequent-elements/mmyeon.js new file mode 100644 index 000000000..7fdce1cb1 --- /dev/null +++ b/top-k-frequent-elements/mmyeon.js @@ -0,0 +1,33 @@ +/** + * 접근 방법 : + * - 숫자 바열을 전체 순회하면서 빈도수를 객체에 저장 + * - 객체 값을 내림차순으로 정렬한 뒤, 원하는 항목만큼 자르고 숫자로 변환한 뒤 리턴하기 + * + * 시간복잡도 : O(nlogn) + * - 숫자 배열 길이 = n , 가져올 항목 개수 = k + * - 객체에 숫자와 빈도수 저장하기 위해서 모든 숫자 순회 : O(n) + * - 객체 키값을 내림차순으로 정렬 : O(nlogn) + * - slice, map : O(k) + * + * 공간복잡도 : + * - 숫자 배열의 길이만큼 객체에 저장하니까 O(n) + */ + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ + +var topKFrequent = function (nums, k) { + const obj = {}; + + for (const num of nums) { + obj[num] = (obj[num] ?? 0) + 1; + } + + return Object.entries(obj) + .sort((a, b) => b[1] - a[1]) + .slice(0, k) + .map((item) => Number(item[0])); +}; From 24faa7dba89c79d8f01493a092108cdbbde0635a Mon Sep 17 00:00:00 2001 From: mmyeon Date: Thu, 12 Dec 2024 21:56:08 +0900 Subject: [PATCH 238/396] add solution : 128. Longest Consecutive Sequence --- longest-common-subsequence/mmyeon.js | 46 ++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 longest-common-subsequence/mmyeon.js diff --git a/longest-common-subsequence/mmyeon.js b/longest-common-subsequence/mmyeon.js new file mode 100644 index 000000000..bc9dfcc47 --- /dev/null +++ b/longest-common-subsequence/mmyeon.js @@ -0,0 +1,46 @@ +/** + * + * 접근 방법 : + * - 중복 숫자 제거한 뒤, 숫자 순회하면서 연속 숫자의 시작 지점인지 체크 + * - 더 작은 숫자가 없으면 현재 숫자가 연속 숫자의 시작 지점이기 때문에, 연속된 다음 큰 숫자가 존재하는지 체크 + * - 있으면 count 증가시키고, 그 다음 숫자 있는지 반복해서 체크 + * - 연속 숫자가 존재하지 않을 때까지 순회하기 + * - count가 maxCount보다 큰 경우 maxCount값을 count 값으로 업데이트 + * + * 시간복잡도 : + * - 숫자 배열 길이를 모두 순회하니까 O(n) + * + * 공간복잡도 : + * - Set을 사용해서 숫자 중복 제거하고 저장하니까 O(n) + */ + +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + // 배열 비어있는 경우 처리 + if (nums.length === 0) return 0; + + const uniqueNums = new Set(nums); + let maxCount = 1; + + for (const num of uniqueNums) { + // 연속된 숫자의 시작 지점인지 체크(더 작은 숫자가 존재하지 않아야 함) + if (!uniqueNums.has(num - 1)) { + let next = num + 1; + let count = 1; + + // 연속 숫자가 더 존재하는지 체크 + while (uniqueNums.has(next)) { + next++; + count++; + } + + // 기존 maxCount보다 크면, count 값으로 업데이트하기 + if (maxCount < count) maxCount = count; + } + } + + return maxCount; +}; From 205ef8213cc493ed055cdec37889dee265e948e7 Mon Sep 17 00:00:00 2001 From: mmyeon Date: Thu, 12 Dec 2024 22:29:16 +0900 Subject: [PATCH 239/396] add solution : 198. House Robber --- house-robber/mmyeon.js | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 house-robber/mmyeon.js diff --git a/house-robber/mmyeon.js b/house-robber/mmyeon.js new file mode 100644 index 000000000..0e4aff237 --- /dev/null +++ b/house-robber/mmyeon.js @@ -0,0 +1,34 @@ +/** + * + * 접근 방법 : dp 사용 + * - 배열 길이가 1개 일때는 첫 번쨰 값 리턴하고, 2개면 더 큰 수를 리턴한다. + * - 3개 부터는 바로 옆집 값에 현재집 값을 더한 값과 옆옆집의 값을 비교해서 큰 값을 계산한다. + * - 다음 집 값에 현재까지의 값 활용하기 위해서, 바로 옆집, 옆옆집 값을 업데이트해준다. + * - 현재 값이 저장된 옆집값을 리턴한다. + * + * 시간복잡도 : + * - 주어진 숫자 배열 길이만큼 1회 순회하니까 O(n) + * + * 공간복잡도 : + * - 옆집과 옆옆집 값을 2개의 변수에 저장해야하니까 O(1) + * + */ +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function (nums) { + if (nums.length === 1) return nums[0]; + if (nums.length === 2) return Math.max(nums[0], nums[1]); + + let prevPrevHouse = nums[0]; + let prevHouse = Math.max(nums[0], nums[1]); + + for (let i = 2; i < nums.length; i++) { + const current = Math.max(prevHouse, prevPrevHouse + nums[i]); + prevPrevHouse = prevHouse; + prevHouse = current; + } + + return prevHouse; +}; From 94f0b90ece54c2ee7e1152da1e9229578bd341c2 Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Thu, 12 Dec 2024 22:34:57 +0900 Subject: [PATCH 240/396] :art: House Robber Solution --- house-robber/dalpang81.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 house-robber/dalpang81.java diff --git a/house-robber/dalpang81.java b/house-robber/dalpang81.java new file mode 100644 index 000000000..1220ed06c --- /dev/null +++ b/house-robber/dalpang81.java @@ -0,0 +1,18 @@ +class Solution { + public int rob(int[] nums) { + if (nums.length == 1) { + return nums[0]; + } + + int temp2 = nums[0]; + int temp1 = Math.max(nums[0], nums[1]); + + for (int i = 2; i < nums.length; i++) { + int current = Math.max(temp1, nums[i] + temp2); + temp2 = temp1; + temp1 = current; + } + + return temp1; + } +} From ee7246113e6aff0d021af293d1622d2eab720590 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Thu, 12 Dec 2024 23:13:42 +0900 Subject: [PATCH 241/396] feat: valid-palindrome solution --- valid-palindrome/YeomChaeeun.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 valid-palindrome/YeomChaeeun.ts diff --git a/valid-palindrome/YeomChaeeun.ts b/valid-palindrome/YeomChaeeun.ts new file mode 100644 index 000000000..1a2ddc5d9 --- /dev/null +++ b/valid-palindrome/YeomChaeeun.ts @@ -0,0 +1,17 @@ +/** + * palindrom: 회문, 거꾸로 읽어도 제대로 읽는 것과 같은 문장 + * @param s + */ +function isPalindrome(s: string): boolean { + let word = s.toLowerCase(); + const reg = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\" ]/g; + + word = word.replace(reg, ''); + for(let i = 0; i < word.length; i++) { + for(let j = word.length-i-1; j >= word.length-i-1; j--) { + // console.log(word[i], '===', word[j]) + if(word[i] !== word[j]) return false; + } + } + return true; +}; From 1b919499aff67e2b9612f02f88a3f7b8c69a9bf2 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Thu, 12 Dec 2024 23:13:50 +0900 Subject: [PATCH 242/396] feat: top-k-frequent-elements solution --- top-k-frequent-elements/YeomChaeeun.ts | 29 ++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 top-k-frequent-elements/YeomChaeeun.ts diff --git a/top-k-frequent-elements/YeomChaeeun.ts b/top-k-frequent-elements/YeomChaeeun.ts new file mode 100644 index 000000000..efaa6b6e5 --- /dev/null +++ b/top-k-frequent-elements/YeomChaeeun.ts @@ -0,0 +1,29 @@ +/** + * + * @param nums + * @param k + */ +function topKFrequent(nums: number[], k: number): number[] { + let obj = {} + + for(const num of nums) { + if(!obj[num]) + obj[num] = 0 + ++obj[num] + } + + // 배열로 변경 + let entries = Object.entries(obj) + // 정렬 + let sort_arr = entries.sort((a, b) => Number(b[1]) - Number(a[1])); + + let result = []; + let l = 0; + for(const item of sort_arr) { + if(l == k) break; + result.push(Number(item[0])); + l++; + } + + return result; +}; From 243f35d3921d1714b7a0b979c05eb60a2cbfc638 Mon Sep 17 00:00:00 2001 From: yeeZinu Date: Thu, 12 Dec 2024 23:58:04 +0900 Subject: [PATCH 243/396] house robber solution --- house-robber/yeeZinu.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 house-robber/yeeZinu.js diff --git a/house-robber/yeeZinu.js b/house-robber/yeeZinu.js new file mode 100644 index 000000000..d8d80fc83 --- /dev/null +++ b/house-robber/yeeZinu.js @@ -0,0 +1,23 @@ +var rob = function (nums) { + const n = nums.length; + + // 길이가 1이라면 + if (n === 1) { + return nums[0]; + } + + // nums의 길이만큼 0으로 초기화된 배열 + const dp = Array(n).fill(0); + + // 0번은 nums[0] + dp[0] = nums[0]; + // 1번은 0과 1중 큰것을 선택 + dp[1] = Math.max(nums[0], nums[1]); + + // i-1 과 i + i-2 의 합중 더 큰것을 선택하면됨 + for (let i = 2; i < n; i++) { + dp[i] = Math.max(dp[i - 1], nums[i] + dp[i - 2]); + } + // i가 n - 1까지 반복함 + return dp[n - 1]; +}; From c1e8ec3f6079cef65c6dcfca00dee23c84008ff2 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Thu, 12 Dec 2024 23:59:05 +0900 Subject: [PATCH 244/396] feat: longest-consecutive-sequence solution --- longest-consecutive-sequence/YeomChaeeun.ts | 50 +++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 longest-consecutive-sequence/YeomChaeeun.ts diff --git a/longest-consecutive-sequence/YeomChaeeun.ts b/longest-consecutive-sequence/YeomChaeeun.ts new file mode 100644 index 000000000..4e3d0629c --- /dev/null +++ b/longest-consecutive-sequence/YeomChaeeun.ts @@ -0,0 +1,50 @@ +/** + * 가장 긴 연속의 시퀀스 구하기 + * @param nums + */ +function longestConsecutive(nums: number[]): number { + + // length 가 0, 1 인 경우 + if(nums.length < 2) + return nums.length; // 0, 1 + + // 정렬 + nums = nums.sort((a, b) => a - b) + + // 접근 (1) 처음 연속된 count만 리턴함 ============= + // let count = 1 + // for(let i = 0; i < nums.length-1; i++) { + // if(nums[i] === nums[i+1]) { + // continue; + // } else if(nums[i] - nums[i+1] === 1) { + // count++; + // } else { + // break; + // } + // }; + // console.log(count); + // return count; + + // ========= + + let longest = 0; + let temp = 1; + + for(let i = 0; i < nums.length-1; i++) { + if(nums[i] === nums[i + 1]) { + // console.log(nums[i], '===', nums[i+1]) + continue; + } else if(nums[i] + 1 === nums[i + 1] ) { + // console.log(nums[i], '+ 1 =', nums[i+1]) + temp += 1; + } else { + // console.log(longest, ' - ', temp) + longest = Math.max(temp, longest); + temp = 1; + } + } + + // i가 마지막인 경우 for문의 else문을 타지 않으므로 다시 한번 체크함 + longest = Math.max(temp, longest); + return longest; +}; From 593e06a4e1c99c9e55740a1f45945b2e5a73cf51 Mon Sep 17 00:00:00 2001 From: aa601 <152935684+aa601@users.noreply.github.com> Date: Fri, 13 Dec 2024 00:10:23 +0900 Subject: [PATCH 245/396] added line --- valid-palindrome/aa601.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/valid-palindrome/aa601.c b/valid-palindrome/aa601.c index 378261400..83dd4dab3 100644 --- a/valid-palindrome/aa601.c +++ b/valid-palindrome/aa601.c @@ -24,4 +24,4 @@ bool isPalindrome(char* s) { } } return (flag); -} \ No newline at end of file +} From 9a3c3f3ffd635bae7cae181d7cca973fecb6539a Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Fri, 13 Dec 2024 00:11:03 +0900 Subject: [PATCH 246/396] valid-palindrome --- valid-palindrome/taewanseoul.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 valid-palindrome/taewanseoul.ts diff --git a/valid-palindrome/taewanseoul.ts b/valid-palindrome/taewanseoul.ts new file mode 100644 index 000000000..88003d33b --- /dev/null +++ b/valid-palindrome/taewanseoul.ts @@ -0,0 +1,16 @@ +/** + * 125. Valid Palindrome + * A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all + * non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters + * and numbers. + * Given a string s, return true if it is a palindrome, or false otherwise. + * https://leetcode.com/problems/valid-palindrome/description/ + */ +function isPalindrome(s: string): boolean { + const chars = s.replace(/[^a-z0-9]/gi, "").toLowerCase(); + + return chars === [...chars].reverse().join(""); +} + +// O(n) time +// O(n) space From fe2f86d66b9138f8401267bde49640226714412f Mon Sep 17 00:00:00 2001 From: Minji Ko Date: Fri, 13 Dec 2024 00:18:55 +0900 Subject: [PATCH 247/396] =?UTF-8?q?refactor:=20complexity=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80,=20=EA=B3=B5=EA=B0=84=EB=B3=B5=EC=9E=A1=EB=8F=84=20?= =?UTF-8?q?=EA=B0=9C=EC=84=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/minji-go.java | 10 ++++++++++ house-robber/minji-go.java | 20 ++++++++++++++------ longest-consecutive-sequence/minji-go.java | 12 +++++++++++- top-k-frequent-elements/minji-go.java | 21 ++++++++++++++++----- valid-palindrome/minji-go.java | 9 ++++++++- 5 files changed, 59 insertions(+), 13 deletions(-) diff --git a/contains-duplicate/minji-go.java b/contains-duplicate/minji-go.java index a69cdcac0..7a5eb0276 100644 --- a/contains-duplicate/minji-go.java +++ b/contains-duplicate/minji-go.java @@ -1,3 +1,13 @@ +/* + Problem: https://leetcode.com/problems/contains-duplicate/ + Description: return true if any value appears at least twice in the array + Concept: Array, Hash Table, Sorting + Time Complexity: O(n), Runtime: 10ms + Space Complexity: O(n), Memory: 58.6MB +*/ +import java.util.HashSet; +import java.util.Set; + class Solution { public boolean containsDuplicate(int[] nums) { Set count = new HashSet<>(); diff --git a/house-robber/minji-go.java b/house-robber/minji-go.java index 3aa8bdcc6..f7e12b519 100644 --- a/house-robber/minji-go.java +++ b/house-robber/minji-go.java @@ -1,11 +1,19 @@ +/* + Problem: https://leetcode.com/problems/house-robber/ + Description: the maximum amount of money you can rob if you cannot rob two adjacent houses + Concept: Array, Dynamic Programming + Time Complexity: O(n), Runtime: 0ms + Space Complexity: O(1), Memory: 41.42MB +*/ class Solution { public int rob(int[] nums) { - int[] sum = new int[nums.length+1]; - sum[0] = nums[0]; - if(nums.length>1) sum[1] = Math.max(nums[0], nums[1]); + int sum1 = nums[0]; + int sum2 = nums.length>1? Math.max(nums[0], nums[1]) : nums[0]; for(int i=2; i set = new HashSet<>(); @@ -7,7 +17,7 @@ public int longestConsecutive(int[] nums) { int answer = 0; for(int num: nums){ - if(set.contains(num-1)){ + if(set.contains(num-1)){ //contains(): O(1) continue; } int length = 1; diff --git a/top-k-frequent-elements/minji-go.java b/top-k-frequent-elements/minji-go.java index 9d2e8bc8a..b10cd1231 100644 --- a/top-k-frequent-elements/minji-go.java +++ b/top-k-frequent-elements/minji-go.java @@ -1,17 +1,28 @@ +/* + Problem: https://leetcode.com/problems/top-k-frequent-elements/ + Description: return the k most frequent elements + Concept: Array, Hash Table, Divide and Conquer, Sorting, Heap (Priority Queue), Bucket Sort, Counting, Quickselect + Time Complexity: O(n log k), Runtime: 15ms + Space Complexity: O(n), Memory: 48.64MB +*/ +import java.util.*; + class Solution { public int[] topKFrequent(int[] nums, int k) { Map count = new HashMap<>(); for(int num : nums){ count.put(num, count.getOrDefault(num, 0)+1); } - List tops = count.keySet().stream() - .sorted((i1, i2) -> count.get(i2)-count.get(i1)) - .limit(k) - .toList(); + + PriorityQueue pq = new PriorityQueue<>(Comparator.comparingInt(count::get)); + for (int num : count.keySet()) { + pq.offer(num); + if (pq.size() > k) pq.poll(); + } int[] answer = new int[k]; for(int i=0; i Date: Fri, 13 Dec 2024 00:20:04 +0900 Subject: [PATCH 248/396] =?UTF-8?q?refactor:=20=EA=B0=9C=ED=96=89=EB=AC=B8?= =?UTF-8?q?=EC=9E=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- house-robber/minji-go.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/house-robber/minji-go.java b/house-robber/minji-go.java index f7e12b519..a98bc2461 100644 --- a/house-robber/minji-go.java +++ b/house-robber/minji-go.java @@ -16,4 +16,4 @@ public int rob(int[] nums) { } return sum2; } -} \ No newline at end of file +} From b31642f7536b60a908d90bdd1bfc3459165ada43 Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Fri, 13 Dec 2024 00:38:18 +0900 Subject: [PATCH 249/396] refactor: contains-duplicate --- contains-duplicate/taewanseoul.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/contains-duplicate/taewanseoul.ts b/contains-duplicate/taewanseoul.ts index 97233136c..85a3992a0 100644 --- a/contains-duplicate/taewanseoul.ts +++ b/contains-duplicate/taewanseoul.ts @@ -4,9 +4,16 @@ * https://leetcode.com/problems/contains-duplicate/description/ */ function containsDuplicate(nums: number[]): boolean { - const isDuped = new Set(nums).size !== nums.length; + const set = new Set(); - return isDuped ? true : false; + for (let i = 0; i < nums.length; i++) { + if (set.has(nums[i])) { + return true; + } + set.add(nums[i]); + } + + return false; } // TC: O(n) From f3326a8132c709b9bb91ac9db39f933db1a17949 Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Fri, 13 Dec 2024 00:43:52 +0900 Subject: [PATCH 250/396] top-k-frequent-elements --- top-k-frequent-elements/taewanseoul.ts | 31 ++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 top-k-frequent-elements/taewanseoul.ts diff --git a/top-k-frequent-elements/taewanseoul.ts b/top-k-frequent-elements/taewanseoul.ts new file mode 100644 index 000000000..71b317398 --- /dev/null +++ b/top-k-frequent-elements/taewanseoul.ts @@ -0,0 +1,31 @@ +/** + * 347. Top K Frequent Elements + * Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in + * any order. + * https://leetcode.com/problems/top-k-frequent-elements/description/ + */ +function topKFrequent(nums: number[], k: number): number[] { + const map = new Map(); + + nums.forEach((n) => { + const count = map.get(n); + if (count) { + map.set(n, count + 1); + return; + } + map.set(n, 1); + }); + + const kvArray = [...map]; + const sorted = kvArray.sort(([, v1], [, v2]) => v2 - v1); + + const result: number[] = []; + for (let i = 0; i < k; i++) { + result.push(sorted[i][0]); + } + + return result; +} + +// O(n) time +// O(n) space From f3a9a4abcd4e227485092f082363e04c5e58839f Mon Sep 17 00:00:00 2001 From: aa601 Date: Fri, 13 Dec 2024 01:31:23 +0900 Subject: [PATCH 251/396] add : solution house-robber --- house-robber/aa601.c | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 house-robber/aa601.c diff --git a/house-robber/aa601.c b/house-robber/aa601.c new file mode 100644 index 000000000..3e3ef85a8 --- /dev/null +++ b/house-robber/aa601.c @@ -0,0 +1,40 @@ +int rob(int* nums, int numsSize) { + int *dp; + int max; + int i; + int j; + + // dp에 nums 복사 + dp = malloc(sizeof(int) * numsSize); + if (!dp) + return (0); + i = -1; + while (++i < numsSize) { + dp[i] = nums[i]; + } + + // dp 시작 + i = 0; + j = 0; + while (++i < numsSize) { + j = 0; + max = dp[i]; + while (j + 1 < i) { + if (max < dp[i] + dp[j]) + max = dp[i] + dp[j]; + ++j; + } + dp[i] = max; + } + + // dp 배열의 최종 max값 리턴 + i = -1; + max = dp[0]; + while (++i < numsSize) { + if (max < dp[i]) + max = dp[i]; + } + free(dp); + return (max); +} + From fde8195823218d11099a4dbb2e5bc24e57c32b8e Mon Sep 17 00:00:00 2001 From: sungjinwi <0202wsj@gmail.com> Date: Fri, 13 Dec 2024 01:33:46 +0900 Subject: [PATCH 252/396] house-robber solution --- house-robber/sungjinwi.c | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 house-robber/sungjinwi.c diff --git a/house-robber/sungjinwi.c b/house-robber/sungjinwi.c new file mode 100644 index 000000000..e7d9d386b --- /dev/null +++ b/house-robber/sungjinwi.c @@ -0,0 +1,35 @@ +#include +#include + +/* + 시간복잡도 + + 이중for문 + => O(N^2) + + 공간복잡도 + + dp만큼 malloc + => O(N) +*/ + +int rob(int* nums, int numsSize) { + int *dp; + int max_before; + int max = 0; + + dp = malloc(numsSize * sizeof(int)); + for (int i = 0; i < numsSize; i++) + { + max_before = 0; + for (int j = 0; j < i - 1; j++) + if (dp[j] > max_before) + max_before = dp[j]; + dp[i] = nums[i] + max_before; + } + for (int i = 0; i < numsSize; i++) + if (dp[i] > max) + max = dp[i]; + free(dp); + return (max); +} From 054e552d129c239893b917e28e1909bacd154b75 Mon Sep 17 00:00:00 2001 From: Taewan Lim Date: Fri, 13 Dec 2024 01:52:54 +0900 Subject: [PATCH 253/396] longest-consecutive-sequence --- longest-consecutive-sequence/taewanseoul.ts | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 longest-consecutive-sequence/taewanseoul.ts diff --git a/longest-consecutive-sequence/taewanseoul.ts b/longest-consecutive-sequence/taewanseoul.ts new file mode 100644 index 000000000..4d6c9cd1e --- /dev/null +++ b/longest-consecutive-sequence/taewanseoul.ts @@ -0,0 +1,33 @@ +/** + * 128. Longest Consecutive Sequence + * Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. + * + * You must write an algorithm that runs in O(n) time. + * https://leetcode.com/problems/longest-consecutive-sequence/description/ + */ +function longestConsecutive(nums: number[]): number { + const set = new Set(nums); + const sorted = [...set].sort((a, b) => a - b); + + if (sorted.length === 0) { + return 0; + } + + let longestSequence = 1; + let currentSequence = 1; + for (let i = 0; i - 1 < sorted.length; i++) { + if (Math.abs(sorted[i + 1] - sorted[i]) === 1) { + currentSequence++; + } else { + if (currentSequence > longestSequence) { + longestSequence = currentSequence; + } + currentSequence = 1; + } + } + + return longestSequence; +} + +// O(n) time +// O(n) space From 947ca5b44a9671de8c1b2e23fa1f86075c6586a0 Mon Sep 17 00:00:00 2001 From: suhacs Date: Thu, 12 Dec 2024 14:27:35 -0500 Subject: [PATCH 254/396] valid-palindrome --- valid-palindrome/suhacs.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 valid-palindrome/suhacs.js diff --git a/valid-palindrome/suhacs.js b/valid-palindrome/suhacs.js new file mode 100644 index 000000000..cc4508004 --- /dev/null +++ b/valid-palindrome/suhacs.js @@ -0,0 +1,12 @@ +function isValidPalindrome(text) { + let refinedTxt = text + .replaceAll(/[^a-zA-Z0-9]/g, "") + .replaceAll(" ", "") + .toLowerCase(); + console.log(refinedTxt === [...refinedTxt].reverse().join("") ? true : false); + return refinedTxt === [...refinedTxt].reverse().join("") ? true : false; +} + +isValidPalindrome("A man, a plan, a canal: Panama"); //true +isValidPalindrome("race a car"); //false +isValidPalindrome(" "); //true From 73cd02d29e27a8b725a5dcc013000ce1c5f202d3 Mon Sep 17 00:00:00 2001 From: Gunwoo Baik Date: Fri, 13 Dec 2024 06:32:37 +0900 Subject: [PATCH 255/396] refactor: Remove unnecessary function Co-authored-by: Dongyeong Chon --- valid-palindrome/gwbaik9717.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/valid-palindrome/gwbaik9717.js b/valid-palindrome/gwbaik9717.js index 890929a89..4e2ac5871 100644 --- a/valid-palindrome/gwbaik9717.js +++ b/valid-palindrome/gwbaik9717.js @@ -6,11 +6,7 @@ * @return {boolean} */ var isPalindrome = function (s) { - const normalize = (s) => { - return s.toLowerCase().replace(/[^a-z0-9]/g, ""); - }; - - const normalized = normalize(s); + const normalized = s.toLowerCase().replace(/[^a-z0-9]/g, ""); const reversed = normalized.split("").reverse().join(""); return normalized === reversed; From 958eaf193dfb21f52663345a348e29e002921b5b Mon Sep 17 00:00:00 2001 From: suhacs Date: Thu, 12 Dec 2024 16:57:41 -0500 Subject: [PATCH 256/396] top-k-frequent-elements : still working --- top-k-frequent-elements/suhacs.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 top-k-frequent-elements/suhacs.js diff --git a/top-k-frequent-elements/suhacs.js b/top-k-frequent-elements/suhacs.js new file mode 100644 index 000000000..13bf4d287 --- /dev/null +++ b/top-k-frequent-elements/suhacs.js @@ -0,0 +1,14 @@ +// Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. + +function top_k_frequent_element(numArr, k) { + let element_qty = []; + const numSet = [...new Set(numArr)]; + for (num of numSet) { + const count = numArr.filter((x) => x === num).length; + element_qty.push({ [num]: count }); + } + Object.keys(element_qty).forEach((key) => element_qty[key]); +} + +const Arr = [1, 2, 3, 4, 5, 5, 5, 5, 3, 3, 32, 2, 2, 1]; +top_k_frequent_element(Arr); From b58d47d2fa8fb6df21e4205ce31c5d4f12f542ca Mon Sep 17 00:00:00 2001 From: GangBean Date: Fri, 13 Dec 2024 07:21:11 +0900 Subject: [PATCH 257/396] solve: house robber --- house-robber/GangBean.java | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 house-robber/GangBean.java diff --git a/house-robber/GangBean.java b/house-robber/GangBean.java new file mode 100644 index 000000000..c5138dd02 --- /dev/null +++ b/house-robber/GangBean.java @@ -0,0 +1,28 @@ +class Solution { + public int rob(int[] nums) { + /** + r[0] = a[0] + r[1] = max(a[1], r[0]) + r[2] = max(r[1], a[2] + r[0]) + r[3] = max(r[2], a[3] + r[1]) + ... + r[k] = max(r[k-1], a[k] + r[k-2]) O(1) + */ + int[] r = new int[nums.length]; + + for (int i = 0; i < nums.length; i++) { // O(N) + if (i == 0) { + r[i] = nums[i]; + continue; + } + if (i == 1) { + r[i] = Math.max(nums[i], r[i-1]); + continue; + } + r[i] = Math.max(r[i-1], nums[i] + r[i-2]); + } + + return r[nums.length - 1]; + } +} + From 15c12783d85fbe09fd13cc08bfcb175b88ab6ceb Mon Sep 17 00:00:00 2001 From: Jinho Hyeon Date: Fri, 13 Dec 2024 09:59:54 +0900 Subject: [PATCH 258/396] [jinho] Week 1 (#632) * neverlish: week01 * refactor: optimize result slice initialization in topKFrequent function * docs: add time and space complexity comments to algorithms --- contains-duplicate/neverlish.go | 33 ++++++++++++++++ house-robber/neverlish.go | 44 +++++++++++++++++++++ longest-consecutive-sequence/neverlish.go | 48 +++++++++++++++++++++++ top-k-frequent-elements/neverlish.go | 43 ++++++++++++++++++++ valid-palindrome/neverlish.go | 45 +++++++++++++++++++++ 5 files changed, 213 insertions(+) create mode 100644 contains-duplicate/neverlish.go create mode 100644 house-robber/neverlish.go create mode 100644 longest-consecutive-sequence/neverlish.go create mode 100644 top-k-frequent-elements/neverlish.go create mode 100644 valid-palindrome/neverlish.go diff --git a/contains-duplicate/neverlish.go b/contains-duplicate/neverlish.go new file mode 100644 index 000000000..4c3ce0244 --- /dev/null +++ b/contains-duplicate/neverlish.go @@ -0,0 +1,33 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +package main + +import "testing" + +func Test(t *testing.T) { + result1 := containsDuplicate([]int{1, 2, 3, 1}) + + if result1 != true { + t.Fatal("failed test1") + } + + result2 := containsDuplicate([]int{1, 2, 3, 4}) + + if result2 != false { + t.Fatal("failed test2") + } +} + +func containsDuplicate(nums []int) bool { + data := make(map[int]bool) + + for _, num := range nums { + if data[num] { + return true + } else { + data[num] = true + } + } + return false +} diff --git a/house-robber/neverlish.go b/house-robber/neverlish.go new file mode 100644 index 000000000..ee7402a60 --- /dev/null +++ b/house-robber/neverlish.go @@ -0,0 +1,44 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +package main + +import ( + "testing" +) + +func Test(t *testing.T) { + result1 := rob([]int{1, 2, 3, 1}) + + if result1 != 4 { + t.Fatal("failed test1") + } + + result2 := rob([]int{2, 7, 9, 3, 1}) + + if result2 != 12 { + t.Fatal("failed test2") + } +} + +func rob(nums []int) int { + length := len(nums) + + if length == 0 { + return 0 + } + if length == 1 { + return nums[0] + } + + moneys := make([]int, length) + + moneys[0] = nums[0] + moneys[1] = max(nums[0], nums[1]) + + for position := 2; position < length; position++ { + moneys[position] = max(moneys[position-1], moneys[position-2]+nums[position]) + } + + return moneys[length-1] +} diff --git a/longest-consecutive-sequence/neverlish.go b/longest-consecutive-sequence/neverlish.go new file mode 100644 index 000000000..c74dc1a20 --- /dev/null +++ b/longest-consecutive-sequence/neverlish.go @@ -0,0 +1,48 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +package main + +import "testing" + +func Test(t *testing.T) { + result := longestConsecutive([]int{100, 4, 200, 1, 3, 2}) + + if result != 4 { + t.Fatal("failed test") + } + + result2 := longestConsecutive([]int{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}) + + if result2 != 9 { + t.Fatal("failed test2") + } +} + +func longestConsecutive(nums []int) int { + numsSet := make(map[int]bool) + + for _, num := range nums { + numsSet[num] = true + } + + longest := 0 + + for num := range numsSet { + if !numsSet[num-1] { + currentNum := num + currentLength := 1 + + for numsSet[currentNum+1] { + currentNum++ + currentLength++ + } + + if currentLength > longest { + longest = currentLength + } + } + } + + return longest +} diff --git a/top-k-frequent-elements/neverlish.go b/top-k-frequent-elements/neverlish.go new file mode 100644 index 000000000..6c05280be --- /dev/null +++ b/top-k-frequent-elements/neverlish.go @@ -0,0 +1,43 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +package main + +import "testing" + +func Test(t *testing.T) { + result := topKFrequent([]int{1, 1, 1, 2, 2, 3}, 2) + + if result[0] != 1 || result[1] != 2 { + t.Fatal("failed test") + } +} + +func topKFrequent(nums []int, k int) []int { + freq := make(map[int]int) + + for _, num := range nums { + freq[num]++ + } + + freq_by_counts := make(map[int][]int) + + for num, count := range freq { + if _, ok := freq_by_counts[count]; !ok { + freq_by_counts[count] = []int{} + } + freq_by_counts[count] = append(freq_by_counts[count], num) + } + + result := make([]int, 0, k) + + for count := len(nums); count > 0; count-- { + if nums, ok := freq_by_counts[count]; ok { + if len(result) >= k { + break + } + result = append(result, nums...) + } + } + return result +} diff --git a/valid-palindrome/neverlish.go b/valid-palindrome/neverlish.go new file mode 100644 index 000000000..fbaf341a9 --- /dev/null +++ b/valid-palindrome/neverlish.go @@ -0,0 +1,45 @@ +// 시간복잡도: O(n) +// 공간복잡도: O(n) + +package main + +import ( + "strings" + "testing" +) + +func Test(t *testing.T) { + result1 := isPalindrome("A man, a plan, a canal: Panama") + if result1 != true { + t.Fatal("failed test1") + } + + result2 := isPalindrome("race a car") + if result2 != false { + t.Fatal("failed test2") + } + + result3 := isPalindrome("") + + if result3 != true { + t.Fatal("failed test3") + } +} + +func isPalindrome(s string) bool { + s = strings.ToLower(s) + + var filtered []rune + for _, r := range s { + if ('a' <= r && r <= 'z') || ('0' <= r && r <= '9') { + filtered = append(filtered, r) + } + } + + for index, r := range filtered[:len(filtered)/2] { + if r != filtered[len(filtered)-index-1] { + return false + } + } + return true +} From b487b4eadedf997b4d2b9f2f3b0e07928a20680f Mon Sep 17 00:00:00 2001 From: bus710 Date: Thu, 12 Dec 2024 17:32:02 -0800 Subject: [PATCH 259/396] contains duplicate --- contains-duplicate/bus710.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 contains-duplicate/bus710.go diff --git a/contains-duplicate/bus710.go b/contains-duplicate/bus710.go new file mode 100644 index 000000000..d62bc7aec --- /dev/null +++ b/contains-duplicate/bus710.go @@ -0,0 +1,14 @@ +package week01 + +func containsDuplicate(nums []int) bool { + dup := make(map[int]bool, 0) + for _, n := range nums { + if _, ok := dup[n]; !ok { + dup[n] = true + } else { + return true + } + } + + return false +} From 289c07e9378ca73055fe164be6fc3094dcb9fa4a Mon Sep 17 00:00:00 2001 From: bus710 Date: Thu, 12 Dec 2024 17:39:31 -0800 Subject: [PATCH 260/396] comments --- contains-duplicate/bus710.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/contains-duplicate/bus710.go b/contains-duplicate/bus710.go index d62bc7aec..c0f2179e3 100644 --- a/contains-duplicate/bus710.go +++ b/contains-duplicate/bus710.go @@ -1,5 +1,11 @@ +// 주어진 배열을 선형 순회 하므로, 시간 복잡도와 공간 복잡도 모두 O(n)일 것으로 생각합니다. + package week01 +// 주어진 배열 nums를 순회하며 준비한 맵에 표시를 하되, +// - 키값에 해당하는 값이 없으면 맵의 해당 키값에 true를 저장하고 +// - 키값에 해당하는 값이 있으면 즉시 true를 반환. +// - 순회 후에도 반환하지 않은 경우 중복이 발견되지 않았으므로 false를 반환. func containsDuplicate(nums []int) bool { dup := make(map[int]bool, 0) for _, n := range nums { From 0c04f6e66dc2c44ddba5fbe32d1839cfb9a6e657 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 12:27:37 +0900 Subject: [PATCH 261/396] Contains Duplicate --- contains-duplicate/forest000014.java | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 contains-duplicate/forest000014.java diff --git a/contains-duplicate/forest000014.java b/contains-duplicate/forest000014.java new file mode 100644 index 000000000..125e0e0a8 --- /dev/null +++ b/contains-duplicate/forest000014.java @@ -0,0 +1,26 @@ +/* +Runtime: 10 ms(Beats: 89.16 %) +Time Complexity: O(n) +- HashSet r/w : O(1) +- nums iteration : ( O(1) + O(1) ) * n = O(n) + +Memory: 58.63 MB(Beats: 22.32 %) +Space Complexity: O(n) +*/ + + +class Solution { + public boolean containsDuplicate(int[] nums) { + Set set = new HashSet<>(); + + for (int num: nums) { + if (set.contains(num)) { + return true; + } + + set.add(num); + } + + return false; + } +} From db404bae1ef98fdd44915725460835977e5ed65a Mon Sep 17 00:00:00 2001 From: choidabom Date: Fri, 13 Dec 2024 12:40:14 +0900 Subject: [PATCH 262/396] 220. Valid Palindrome --- valid-palindrome/choidabom.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 valid-palindrome/choidabom.js diff --git a/valid-palindrome/choidabom.js b/valid-palindrome/choidabom.js new file mode 100644 index 000000000..fc89ccc53 --- /dev/null +++ b/valid-palindrome/choidabom.js @@ -0,0 +1,28 @@ +/** + * Runtime: 7ms, Memory: 55.02MB + * + * Time Complexity: O(n) + * Space Complexity: O(n) +*/ + +/** + * @param {string} s + * @return {boolean} + */ +function isPalindrome(s) { + const alphanumeric = getAlphanumeric(s) + return alphanumeric === alphanumeric.split("").reverse().join("") +} + +function getAlphanumeric(string) { + const number = /[0-9]/ + const alphabet = /[a-zA-Z]/ + let alphanumeric = [] + + for (const str of string) { + if (number.test(str) || alphabet.test(str)) { + alphanumeric.push(str) + } + } + return alphanumeric.join("").toLowerCase() +} From 096914a71101655b4052bf8cdfed59523d8feaf3 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 12:55:06 +0900 Subject: [PATCH 263/396] Valid Palindrome --- valid-palindrome/forest000014.java | 41 ++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 valid-palindrome/forest000014.java diff --git a/valid-palindrome/forest000014.java b/valid-palindrome/forest000014.java new file mode 100644 index 000000000..131282a8c --- /dev/null +++ b/valid-palindrome/forest000014.java @@ -0,0 +1,41 @@ +/* +Runtime: 1 ms(Beats: 100.00 %) +Time Complexity: O(n) + +Memory: 43.00 MB(Beats: 64.54 %) +Space Complexity: O(1) +... 문제에서 주어진 String s는 space complexity 계산에서 제외하고, 제가 추가한 변수에 대해서만 계산하면 될까요? +*/ + +class Solution { + public boolean isPalindrome(String s) { + for (int i = 0, j = s.length() - 1; i < j; i++, j--) { + char a = s.charAt(i); + while (a < '0' || (a > '9' && a < 'A') || (a > 'Z' && a < 'a') || a > 'z') { + a = s.charAt(++i); + if (i >= j) { + return true; + } + } + if (a <= 'Z') { + a += ('a' - 'A'); + } + + char b = s.charAt(j); + while (b < '0' || (b > '9' && b < 'A') || (b > 'Z' && b < 'a') || b > 'z') { + b = s.charAt(--j); + if (i >= j) { + return true; + } + } + if (b <= 'Z') { + b += ('a' - 'A'); + } + + if (a != b) { + return false; + } + } + return true; + } +} \ No newline at end of file From d2d0e7d6b2fc34655c1ad3f1d44cfd08ef6c9956 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 12:59:29 +0900 Subject: [PATCH 264/396] Top K Frequent Elements --- top-k-frequent-elements/forest000014.java | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 top-k-frequent-elements/forest000014.java diff --git a/top-k-frequent-elements/forest000014.java b/top-k-frequent-elements/forest000014.java new file mode 100644 index 000000000..baa576432 --- /dev/null +++ b/top-k-frequent-elements/forest000014.java @@ -0,0 +1,52 @@ +/* +Runtime: 10 ms(Beats: 95.83 %) +Time Complexity: O(nlogn) +- map에 item 추가 : O(n) +- items 배열 정렬 : O(nlogn) +- result 배열에 원소 추가 : O(n) + +Memory: 49.50 MB(Beats: 6.84 %) +Space Complexity: O(n) +- map : O(n) +- items : O(n) +- result : O(n) +*/ + +class Solution { + class Item { + int val; + int cnt; + + public Item(int val, int cnt) { + this.val = val; + this.cnt = cnt; + } + + public void plusOne() { + this.cnt += 1; + } + } + + public int[] topKFrequent(int[] nums, int k) { + Map map = new HashMap<>(); + for (int num : nums) { + Item item = map.get(num); + if (item == null) { + item = new Item(num, 1); + map.put(num, item); + } else { + item.plusOne(); + } + } + + ArrayList items = new ArrayList<>(map.values()); + Collections.sort(items, (item1, item2) -> Integer.compare(item2.cnt, item1.cnt)); + + int[] result = new int[k]; + for (int i = 0; i < k; i++) { + result[i] = items.get(i).val; + } + + return result; + } +} \ No newline at end of file From 4409730f7bf3f987061dacf4f5d17c1fe4e1bbe8 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 13:02:43 +0900 Subject: [PATCH 265/396] House Robber --- house-robber/forest000014.java | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 house-robber/forest000014.java diff --git a/house-robber/forest000014.java b/house-robber/forest000014.java new file mode 100644 index 000000000..76926a3ae --- /dev/null +++ b/house-robber/forest000014.java @@ -0,0 +1,23 @@ +/* +Runtime: 0 ms(Beats: 100.00 %) +Time Complexity: O(nlogn) +- nums iteration : O(n) + +Memory: 41.40 MB(Beats: 43.05 %) +Space Complexity: O(n) +- dp[n][2] : O(n) * 2 = O(n) +*/ + +class Solution { + public int rob(int[] nums) { + int[][] dp = new int[nums.length][2]; + + dp[0][1] = nums[0]; + for (int i = 1; i < nums.length; i++) { + dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); + dp[i][1] = dp[i - 1][0] + nums[i]; + } + + return Math.max(dp[nums.length - 1][0], dp[nums.length - 1][1]); + } +} \ No newline at end of file From 3879c7b8302f05d290986d0f614b323dbb54a43b Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 11 Dec 2024 22:10:07 -0500 Subject: [PATCH 266/396] contains-duplicate --- contains-duplicate/Jay-Mo-99.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 contains-duplicate/Jay-Mo-99.py diff --git a/contains-duplicate/Jay-Mo-99.py b/contains-duplicate/Jay-Mo-99.py new file mode 100644 index 000000000..0f2b02747 --- /dev/null +++ b/contains-duplicate/Jay-Mo-99.py @@ -0,0 +1,12 @@ +class Solution(object): + def containsDuplicate(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + #sets don't allow duplicate elements. + #If the length of the set created from nums is different from the original list(nums), It means there are duplicates. + if len(list(set(nums))) == len(nums): + return False + else: + return True \ No newline at end of file From c12452bc1a1ee77253eaccebb1eeabed14bbb02a Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 11 Dec 2024 22:33:34 -0500 Subject: [PATCH 267/396] contains-duplicate --- contains-duplicate/Jay-Mo-99.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/contains-duplicate/Jay-Mo-99.py b/contains-duplicate/Jay-Mo-99.py index 0f2b02747..d924eab7e 100644 --- a/contains-duplicate/Jay-Mo-99.py +++ b/contains-duplicate/Jay-Mo-99.py @@ -4,8 +4,19 @@ def containsDuplicate(self, nums): :type nums: List[int] :rtype: bool """ + #?? #sets don't allow duplicate elements. #If the length of the set created from nums is different from the original list(nums), It means there are duplicates. + + #Big O + #N: ??? ?? nums? ??(Length of the input list nums) + # + #Time Complexity: O(N) + #- set? nums? ?? n? ???? ????(Creating a set from nums): O(N) + #- ??? list? ?? nums?? ??? ??(Comparing the lengths between created list and original list) : O(1) + # + #Space Complexity: O(N) + #-set? nums? ??? ?? ????? n? ????(The set requires extra space depends on the size of nums) : O(N) if len(list(set(nums))) == len(nums): return False else: From 326d2901004ea116a259c7c28bc7d2c78d55ea0a Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 11 Dec 2024 22:34:30 -0500 Subject: [PATCH 268/396] contains-duplicate --- contains-duplicate/Jay-Mo-99.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/contains-duplicate/Jay-Mo-99.py b/contains-duplicate/Jay-Mo-99.py index d924eab7e..9b11678d7 100644 --- a/contains-duplicate/Jay-Mo-99.py +++ b/contains-duplicate/Jay-Mo-99.py @@ -1,22 +1,23 @@ -class Solution(object): +class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ - #?? - #sets don't allow duplicate elements. + #해석 + #sets는 복수 요소를 허용하지 않는다(sets don't allow duplicate elements.) + #만약 set에 기반된 list가 기존 nums와 길이가 다르다면 duplicate element가 있었다는 뜻이다. #If the length of the set created from nums is different from the original list(nums), It means there are duplicates. #Big O - #N: ??? ?? nums? ??(Length of the input list nums) - # + #N: 주어진 배열 nums의 길이(Length of the input list nums) + #Time Complexity: O(N) - #- set? nums? ?? n? ???? ????(Creating a set from nums): O(N) - #- ??? list? ?? nums?? ??? ??(Comparing the lengths between created list and original list) : O(1) - # + #- set은 nums의 길이 n에 기반하여 생성된다(Creating a set from nums): O(N) + #- 생성된 list와 기존 nums와의 비교는 상수(Comparing the lengths between created list and original list) : O(1) + #Space Complexity: O(N) - #-set? nums? ??? ?? ????? n? ????(The set requires extra space depends on the size of nums) : O(N) + #-set은 nums의 길이에 의해 생성되므로 n에 영향받음(The set requires extra space depends on the size of nums) : O(N) if len(list(set(nums))) == len(nums): return False else: From 85f70d11db9023297a46682b0cd4bf2270cca2f9 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 12 Dec 2024 01:09:03 -0500 Subject: [PATCH 269/396] solve: valid-palindrome --- valid-palindrome/Jay-Mo-99.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 valid-palindrome/Jay-Mo-99.py diff --git a/valid-palindrome/Jay-Mo-99.py b/valid-palindrome/Jay-Mo-99.py new file mode 100644 index 000000000..48fc8bca7 --- /dev/null +++ b/valid-palindrome/Jay-Mo-99.py @@ -0,0 +1,31 @@ +# --- 해석 --- +#매개변수 s를 소문자로 변환 후 non alpha numeric(알파벳과 숫자 이외의 모든 것)을 제거하고 빈칸을 replace로 제거한 후 temp에 저장한다 +#temp와 temp를 뒤집힌 string(temp[::-1])을 비교하여, 둘이 같으면 palindrome이다. + +# --- Big O +#N: 매개변수 s의 길이가 N이다. + +# Time Complexity: O(N) +#- temp는 s의 길이에 기반하여 생성된다: O(N) +#- 문자열 뒤집기(temp[::-1])도 s의 길이에 기반한다 : O(N) +#- temp == temp[::-1]는 두 문자열이 길이와 문자 하나하나가 같은지 확인 :O(N) + +# Space Complexity: O(N) +#-temp는 s의 길이에 의해 생성되므로 n에 영향받음(The temp requires extra space depends on the size of s) : O(N) + +class Solution(object): + def isPalindrome(self, s): + """ + :type s: str + :rtype: bool + """ + + #removes all non alpha numeric(only accept alphabet and number) items from the s + temp = lower(s) + temp = " ".join(re.split("[^a-zA-Z0-9]*",temp)).replace(" ","") + #Compare with temp and reverse temp + #If they are same, it is palindrome + if temp == temp[::-1]: + return True + else: + return False \ No newline at end of file From f82a7797f734c35e48bfd3491ca297dd71e41ae4 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 12 Dec 2024 01:36:25 -0500 Subject: [PATCH 270/396] Fix: including the Jay-Mo-99.py --- valid-palindrome/Jay-Mo-99.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/valid-palindrome/Jay-Mo-99.py b/valid-palindrome/Jay-Mo-99.py index 48fc8bca7..e17445d5a 100644 --- a/valid-palindrome/Jay-Mo-99.py +++ b/valid-palindrome/Jay-Mo-99.py @@ -28,4 +28,5 @@ def isPalindrome(self, s): if temp == temp[::-1]: return True else: - return False \ No newline at end of file + return False + \ No newline at end of file From 84c6595af29424ff1a0a214ce690944baf5e7e5d Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 12 Dec 2024 01:38:44 -0500 Subject: [PATCH 271/396] Fix: Add missing newline to Python files --- valid-palindrome/Jay-Mo-99.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/valid-palindrome/Jay-Mo-99.py b/valid-palindrome/Jay-Mo-99.py index e17445d5a..c8a516fc5 100644 --- a/valid-palindrome/Jay-Mo-99.py +++ b/valid-palindrome/Jay-Mo-99.py @@ -29,4 +29,10 @@ def isPalindrome(self, s): return True else: return False - \ No newline at end of file + + + + + + + From e35428fdad6e612cec127cc4badc6d325e60152d Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 12 Dec 2024 01:43:03 -0500 Subject: [PATCH 272/396] Fix: Add newline at end of Jay-Mo-99.py --- valid-palindrome/Jay-Mo-99.py | 1 + 1 file changed, 1 insertion(+) diff --git a/valid-palindrome/Jay-Mo-99.py b/valid-palindrome/Jay-Mo-99.py index c8a516fc5..5135cd51d 100644 --- a/valid-palindrome/Jay-Mo-99.py +++ b/valid-palindrome/Jay-Mo-99.py @@ -36,3 +36,4 @@ def isPalindrome(self, s): + From c3bfa2ccb275b70a1f8297ac8a876470edf830d8 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 12 Dec 2024 01:45:34 -0500 Subject: [PATCH 273/396] Fix: Add newline at end of contains-duplicate/Jay-Mo-99.py --- contains-duplicate/Jay-Mo-99.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/Jay-Mo-99.py b/contains-duplicate/Jay-Mo-99.py index 9b11678d7..3e856980c 100644 --- a/contains-duplicate/Jay-Mo-99.py +++ b/contains-duplicate/Jay-Mo-99.py @@ -21,4 +21,4 @@ def containsDuplicate(self, nums): if len(list(set(nums))) == len(nums): return False else: - return True \ No newline at end of file + return True From 60c7a9105327fdbcfc0f146ac6b3f7c969bbd9e1 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 13 Dec 2024 01:32:06 -0500 Subject: [PATCH 274/396] Modified: contains-duplicate/Jay-Mo-99.py --- contains-duplicate/Jay-Mo-99.py | 1 + 1 file changed, 1 insertion(+) diff --git a/contains-duplicate/Jay-Mo-99.py b/contains-duplicate/Jay-Mo-99.py index 3e856980c..584f92469 100644 --- a/contains-duplicate/Jay-Mo-99.py +++ b/contains-duplicate/Jay-Mo-99.py @@ -22,3 +22,4 @@ def containsDuplicate(self, nums): return False else: return True + \ No newline at end of file From 58988dd5efad7d576a5c514894909e5fb1537e68 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 13 Dec 2024 01:35:32 -0500 Subject: [PATCH 275/396] Fix: Add missing newline at EOF --- contains-duplicate/Jay-Mo-99.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contains-duplicate/Jay-Mo-99.py b/contains-duplicate/Jay-Mo-99.py index 584f92469..d33bfde1d 100644 --- a/contains-duplicate/Jay-Mo-99.py +++ b/contains-duplicate/Jay-Mo-99.py @@ -22,4 +22,5 @@ def containsDuplicate(self, nums): return False else: return True - \ No newline at end of file + + From 9877f4270a843cae2737976bd5289df44e7ecbf8 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 13 Dec 2024 01:52:41 -0500 Subject: [PATCH 276/396] Edit: Delete if statement and return condition directely --- contains-duplicate/Jay-Mo-99.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/contains-duplicate/Jay-Mo-99.py b/contains-duplicate/Jay-Mo-99.py index d33bfde1d..25a81a0c0 100644 --- a/contains-duplicate/Jay-Mo-99.py +++ b/contains-duplicate/Jay-Mo-99.py @@ -18,9 +18,6 @@ def containsDuplicate(self, nums): #Space Complexity: O(N) #-set은 nums의 길이에 의해 생성되므로 n에 영향받음(The set requires extra space depends on the size of nums) : O(N) - if len(list(set(nums))) == len(nums): - return False - else: - return True + return len(list(set(nums))) != len(nums) #set된 list와 기존 nums의 len이 일치하지 않는다면 true(duplicate), 아니면 false From 2f505d96055ad6d195f8f350faecfcd0df68db7a Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Thu, 12 Dec 2024 22:54:35 -0800 Subject: [PATCH 277/396] house-robber Solution --- house-robber/Zioq.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 house-robber/Zioq.js diff --git a/house-robber/Zioq.js b/house-robber/Zioq.js new file mode 100644 index 000000000..7134400d0 --- /dev/null +++ b/house-robber/Zioq.js @@ -0,0 +1,27 @@ +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function(nums) { + if( nums.length < 1 ) { return nums[0]} + + let prev_2 = nums[0] + let prev_1 = Math.max(nums[0], nums[1]); + + for( let i= 2; i Date: Fri, 13 Dec 2024 01:55:39 -0500 Subject: [PATCH 278/396] Edit: Delete if statement and return condition directely --- valid-palindrome/Jay-Mo-99.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/valid-palindrome/Jay-Mo-99.py b/valid-palindrome/Jay-Mo-99.py index 5135cd51d..a1753d2f2 100644 --- a/valid-palindrome/Jay-Mo-99.py +++ b/valid-palindrome/Jay-Mo-99.py @@ -25,10 +25,9 @@ def isPalindrome(self, s): temp = " ".join(re.split("[^a-zA-Z0-9]*",temp)).replace(" ","") #Compare with temp and reverse temp #If they are same, it is palindrome - if temp == temp[::-1]: - return True - else: - return False + return temp == temp[::-1] + + From 18a3bd891836bddddf323c4dce8e5c98210a1b99 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Thu, 12 Dec 2024 23:02:02 -0800 Subject: [PATCH 279/396] update code --- contains-duplicate/Zioq.js | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/contains-duplicate/Zioq.js b/contains-duplicate/Zioq.js index 86cf6198d..1854906cb 100644 --- a/contains-duplicate/Zioq.js +++ b/contains-duplicate/Zioq.js @@ -3,15 +3,19 @@ * @return {boolean} */ var containsDuplicate = function(nums) { - let dup_set = new Set(); // Initialize Set - for (let num of nums) { - dup_set.add(num) // Add value into the set (duplicated value will be ignored) - } - - if(dup_set.size !== nums.length) { - return true - } - return false + let dup_set = new Set(nums); // Initialize Set + return dup_set.size !== nums.length + + + /* Previous Code before the review */ + // for (let num of nums) { + // dup_set.add(num) // Add value into the set (duplicated value will be ignored) + // } + + // if(dup_set.size !== nums.length) { + // return true + // } + // return false }; /* From dd6ca48be4da2b1398b0b79b5c9363355acc67eb Mon Sep 17 00:00:00 2001 From: Nayeon Date: Fri, 13 Dec 2024 16:06:21 +0900 Subject: [PATCH 280/396] refactor: Improve time complexity using heap for topKFrequent --- top-k-frequent-elements/KwonNayeon.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/top-k-frequent-elements/KwonNayeon.py b/top-k-frequent-elements/KwonNayeon.py index cdfab0b31..4c11c5c9b 100644 --- a/top-k-frequent-elements/KwonNayeon.py +++ b/top-k-frequent-elements/KwonNayeon.py @@ -18,16 +18,43 @@ - O(n) """ +# Original Solution class Solution: def topKFrequent(self, nums: List[int], k: int) -> List[int]: frequency = {} result = [] + for num in nums: if num in frequency: frequency[num] += 1 else: frequency[num] = 1 + sorted_frequency = sorted(frequency.items(), key=lambda x: x[1], reverse=True) + for i in range(k): result.append(sorted_frequency[i][0]) + + return result + +# Improved Solution using Heap +# Time Complexity: O(n log k) +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + frequency = {} + result = [] + heap = [] + + for num in nums: + if num in frequency: + frequency[num] += 1 + else: + frequency[num] = 1 + + for num, freq in frequency.items(): + heapq.heappush(heap, (-freq, num)) + + for i in range(k): + result.append(heapq.heappop(heap)[1]) + return result From 8ea0678e98b19308528f1090b97846aaa52c7a09 Mon Sep 17 00:00:00 2001 From: Jaehyeon Robert Han Date: Thu, 12 Dec 2024 23:09:19 -0800 Subject: [PATCH 281/396] add line --- house-robber/Zioq.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/house-robber/Zioq.js b/house-robber/Zioq.js index 7134400d0..214adce87 100644 --- a/house-robber/Zioq.js +++ b/house-robber/Zioq.js @@ -25,3 +25,5 @@ SC: O(1) /* Test Case */ console.log(rob([1,2,3,1])); console.log(rob([2,7,9,3,1])); + + From 10cd65a0ca7521a54e8bf33453dbd8a6573acfaa Mon Sep 17 00:00:00 2001 From: helenapark0826 Date: Fri, 13 Dec 2024 01:51:09 -0500 Subject: [PATCH 282/396] Week 1 Solutions: containsDuplicate, validPalindrome, topKFrequentElements and longestConsecutiveSequence --- contains-duplicate/yolophg.py | 18 ++++++++++++++++++ longest-consecutive-sequence/yolophg.py | 25 +++++++++++++++++++++++++ top-k-frequent-elements/yolophg.py | 16 ++++++++++++++++ valid-palindrome/yolophg.py | 12 ++++++++++++ 4 files changed, 71 insertions(+) create mode 100644 contains-duplicate/yolophg.py create mode 100644 longest-consecutive-sequence/yolophg.py create mode 100644 top-k-frequent-elements/yolophg.py create mode 100644 valid-palindrome/yolophg.py diff --git a/contains-duplicate/yolophg.py b/contains-duplicate/yolophg.py new file mode 100644 index 000000000..bd50d5073 --- /dev/null +++ b/contains-duplicate/yolophg.py @@ -0,0 +1,18 @@ +# Time Complexity: O(n) +# Space Complexity: O(n) + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + # set to keep track of duplicates. + duplicates = set() + + # go through each number in the list + for num in nums: + # if it's a duplicate, return true. + if num in duplicates: + return True + # otherwise, add it to the set to check for duplicates. + duplicates.add(num) + + # if finish the loop and don't find duplicates, return false. + return False diff --git a/longest-consecutive-sequence/yolophg.py b/longest-consecutive-sequence/yolophg.py new file mode 100644 index 000000000..09dcbe78d --- /dev/null +++ b/longest-consecutive-sequence/yolophg.py @@ -0,0 +1,25 @@ +# Time Complexity: O(n) +# Space Complexity: O(n) + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + # convert list to set to remove duplicates and allow quick lookups + num_set = set(nums) + longest_streak = 0 + + # loop through each number in the set + for num in num_set: + # only start counting if it's the beginning of a sequence + if num - 1 not in num_set: + current_num = num + current_streak = 1 + + # keep counting while the next number in the sequence exists + while current_num + 1 in num_set: + current_num += 1 + current_streak += 1 + + # update the longest streak found so far + longest_streak = max(longest_streak, current_streak) + + return longest_streak diff --git a/top-k-frequent-elements/yolophg.py b/top-k-frequent-elements/yolophg.py new file mode 100644 index 000000000..1c4272116 --- /dev/null +++ b/top-k-frequent-elements/yolophg.py @@ -0,0 +1,16 @@ +# Time Complexity: O(n log n) +# Space Complexity: O(n) + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + # count how many times each number appears + counts = {} + for num in nums: + counts[num] = counts.get(num, 0) + 1 + + # sort numbers by their count (most frequent first) and grab top k + # counts.get gets the count of num + # reverse=True sorts in descending order + # [:k] gets the first k elements + top_nums = sorted(counts, key=counts.get, reverse=True) + return top_nums[:k] diff --git a/valid-palindrome/yolophg.py b/valid-palindrome/yolophg.py new file mode 100644 index 000000000..cd353634c --- /dev/null +++ b/valid-palindrome/yolophg.py @@ -0,0 +1,12 @@ +# Time Complexity: O(n) +# Space Complexity: O(n) + +class Solution: + def isPalindrome(self, s: str) -> bool: + # clean up the string: remove non-alphanumeric chars and convert to lowercase + # isalnum() checks if the character is alphanumeric + filtered = ''.join(filter(str.isalnum, s)).lower() + + # check if it reads the same forwards and backwards + # filtered[::-1] flips the string + return filtered == filtered[::-1] From dfb6f0c50aa55547bf831d9a6ebb4ba74c9b1895 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Fri, 13 Dec 2024 18:58:06 +0900 Subject: [PATCH 283/396] Fix: Include numeric characters in palindrome check --- valid-palindrome/KwonNayeon.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/valid-palindrome/KwonNayeon.py b/valid-palindrome/KwonNayeon.py index 71509b4ce..b543fc371 100644 --- a/valid-palindrome/KwonNayeon.py +++ b/valid-palindrome/KwonNayeon.py @@ -14,10 +14,10 @@ Time Complexity: - O(n) +Space Complexity: + - O(n) """ class Solution: def isPalindrome(self, s: str) -> bool: - s = re.sub(r'[^a-zA-z]', '', s).lower() - if s == s[::-1]: - return True - return False + s = re.sub(r'[^a-zA-z0-9]', '', s).lower() + if s == s[::-1] From a211d72e4695cfa2ab054490908a2dbfdabd308c Mon Sep 17 00:00:00 2001 From: Nayeon Date: Fri, 13 Dec 2024 19:02:20 +0900 Subject: [PATCH 284/396] Fix: Updated isPalindrome function to return true/false. --- valid-palindrome/KwonNayeon.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/valid-palindrome/KwonNayeon.py b/valid-palindrome/KwonNayeon.py index b543fc371..5bb039da8 100644 --- a/valid-palindrome/KwonNayeon.py +++ b/valid-palindrome/KwonNayeon.py @@ -20,4 +20,7 @@ class Solution: def isPalindrome(self, s: str) -> bool: s = re.sub(r'[^a-zA-z0-9]', '', s).lower() - if s == s[::-1] + if s == s[::-1]: + return True + return False + From f54580f1746b9bb0eb3b10cc73e93a74809fdd5c Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Fri, 13 Dec 2024 20:14:37 +0900 Subject: [PATCH 285/396] feat: 217. Contains Duplicate --- contains-duplicate/HodaeSsi.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 contains-duplicate/HodaeSsi.py diff --git a/contains-duplicate/HodaeSsi.py b/contains-duplicate/HodaeSsi.py new file mode 100644 index 000000000..21c2e5478 --- /dev/null +++ b/contains-duplicate/HodaeSsi.py @@ -0,0 +1,11 @@ +from typing import List + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + dict = {} + for num in nums: + dict[num] = dict.get(num, 0) + 1 + if dict[num] > 1: + return True + return False + From f0db96aa08265957ad10ef1d42dc54048c9c1832 Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Fri, 13 Dec 2024 20:26:04 +0900 Subject: [PATCH 286/396] feat: 347. Top K Frequent Elements --- top-k-frequent-elements/HodaeSsi.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 top-k-frequent-elements/HodaeSsi.py diff --git a/top-k-frequent-elements/HodaeSsi.py b/top-k-frequent-elements/HodaeSsi.py new file mode 100644 index 000000000..a902dd124 --- /dev/null +++ b/top-k-frequent-elements/HodaeSsi.py @@ -0,0 +1,10 @@ +from typing import List + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + dict = {} + for num in nums: + dict[num] = dict.get(num, 0) + 1 + + return sorted(dict.keys(), key=lambda x: dict[x], reverse=True)[:k] + From 46211b9d6013bf0888df6e82021edd1c2dcfdc97 Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Fri, 13 Dec 2024 20:33:24 +0900 Subject: [PATCH 287/396] feat: 125. Valid Palindrome --- valid-palindrome/HodaeSsi.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 valid-palindrome/HodaeSsi.py diff --git a/valid-palindrome/HodaeSsi.py b/valid-palindrome/HodaeSsi.py new file mode 100644 index 000000000..a63636611 --- /dev/null +++ b/valid-palindrome/HodaeSsi.py @@ -0,0 +1,8 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + s = s.lower() + + s = ''.join(filter(str.isalnum, s)) + + return s == s[::-1] + From 71aadcbff1db2e5a40a42c5f1da4084da7548c26 Mon Sep 17 00:00:00 2001 From: mmyeon Date: Fri, 13 Dec 2024 20:33:55 +0900 Subject: [PATCH 288/396] remove unnecessary variable to return directly --- contains-duplicate/mmyeon.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/contains-duplicate/mmyeon.js b/contains-duplicate/mmyeon.js index a11188a21..9af2a45e3 100644 --- a/contains-duplicate/mmyeon.js +++ b/contains-duplicate/mmyeon.js @@ -18,7 +18,5 @@ */ var containsDuplicate = function (nums) { - const uniqueNumbers = new Set(nums); - - return uniqueNumbers.size !== nums.length; + return new Set(nums).size !== nums.length; }; From 1621698127b07c5c85e77f739cf6c3d1c45859bf Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Fri, 13 Dec 2024 20:34:31 +0900 Subject: [PATCH 289/396] feat: 128. Longest Consecutive Sequence --- longest-consecutive-sequence/HodaeSsi.py | 38 ++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 longest-consecutive-sequence/HodaeSsi.py diff --git a/longest-consecutive-sequence/HodaeSsi.py b/longest-consecutive-sequence/HodaeSsi.py new file mode 100644 index 000000000..9ba623c57 --- /dev/null +++ b/longest-consecutive-sequence/HodaeSsi.py @@ -0,0 +1,38 @@ +from typing import List + + +class Node: + def __init__(self, value): + self.value = value + self.parent = None + self.child = None + +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + answer = 0 + dict = {} + + for num in nums: + if dict.get(num) is None: + dict[num] = Node(num) + if dict.get(num + 1) is not None: + dict[num + 1].child = dict[num] + dict[num].parent = dict[num + 1] + + if dict.get(num - 1) is not None: + dict[num].child = dict[num - 1] + dict[num - 1].parent = dict[num] + + for key in dict.keys(): + if dict[key].parent is None: + node = dict[key] + count = 1 + + while node.child is not None: + count += 1 + node = node.child + + answer = max(answer, count) + + return answer + From 6f69170fd8f5c1edfcea04c98e8313daf36791cb Mon Sep 17 00:00:00 2001 From: "daeho.kim" Date: Fri, 13 Dec 2024 20:35:28 +0900 Subject: [PATCH 290/396] feat: 198. House Robber --- house-robber/HodaeSsi.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 house-robber/HodaeSsi.py diff --git a/house-robber/HodaeSsi.py b/house-robber/HodaeSsi.py new file mode 100644 index 000000000..b68bcdc36 --- /dev/null +++ b/house-robber/HodaeSsi.py @@ -0,0 +1,15 @@ +from typing import List + + +class Solution: + def rob(self, nums: List[int]) -> int: + dp = [0] * len(nums) + + for i in range(len(nums)-1, -1, -1): + dpMax = 0 + for j in range(i + 2, len(nums)): + dpMax = max(dpMax, dp[j]) + dp[i] = nums[i] + dpMax + + return max(dp) + From 3230957f4f1bdb602aa7da92d7c7809e1229503c Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 21:46:02 +0900 Subject: [PATCH 291/396] =?UTF-8?q?=EB=A7=88=EC=A7=80=EB=A7=89=EC=A4=84=20?= =?UTF-8?q?=EA=B0=9C=ED=96=89=20=EB=AC=B8=EC=9E=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- house-robber/forest000014.java | 2 +- top-k-frequent-elements/forest000014.java | 2 +- valid-palindrome/forest000014.java | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/house-robber/forest000014.java b/house-robber/forest000014.java index 76926a3ae..55bf75368 100644 --- a/house-robber/forest000014.java +++ b/house-robber/forest000014.java @@ -20,4 +20,4 @@ public int rob(int[] nums) { return Math.max(dp[nums.length - 1][0], dp[nums.length - 1][1]); } -} \ No newline at end of file +} diff --git a/top-k-frequent-elements/forest000014.java b/top-k-frequent-elements/forest000014.java index baa576432..b7ae12abb 100644 --- a/top-k-frequent-elements/forest000014.java +++ b/top-k-frequent-elements/forest000014.java @@ -49,4 +49,4 @@ public int[] topKFrequent(int[] nums, int k) { return result; } -} \ No newline at end of file +} diff --git a/valid-palindrome/forest000014.java b/valid-palindrome/forest000014.java index 131282a8c..0a605a9b2 100644 --- a/valid-palindrome/forest000014.java +++ b/valid-palindrome/forest000014.java @@ -38,4 +38,4 @@ public boolean isPalindrome(String s) { } return true; } -} \ No newline at end of file +} From a6fd4e24fcc4531ae3bc02633fcc740273fe5627 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 22:28:19 +0900 Subject: [PATCH 292/396] Longest Consecutive Sequence --- .../forest000014.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 longest-consecutive-sequence/forest000014.java diff --git a/longest-consecutive-sequence/forest000014.java b/longest-consecutive-sequence/forest000014.java new file mode 100644 index 000000000..d61e16243 --- /dev/null +++ b/longest-consecutive-sequence/forest000014.java @@ -0,0 +1,70 @@ +/* +sol 1. 재귀 호출 + +알고리즘 문제를 오랜만에 풀어서... union-find를 떠올리긴 했으나, 구현 방법이 가물가물해서 원하는 솔루션으로 풀지 못한 것 같습니다. +일단 vis, cnt 와 재귀 호출을 사용해서 union-find와 유사하게 구현하긴 했는데요 (해설을 달면서 다시 보니 이것도 union-find를 구현하는 한 방법이라고 할 수 있을듯...?), +시간이 된다면 좀 더 최적화한 솔루션을 제출해보겠습니다. + +Runtime: 98 ms(Beats: 35.68 %) +Time Complexity: O(n) +- set, vis, cnt 생성 : O(n) +- set의 모든 원소를 순회하면서 checkAbove 수행 : O(n) + - checkAbove(x)는 x를 1번째 원소로 하는, 증가하는 연속 수열의 길이를 반환함 + - checkAbove(x)는 재귀적으로 checkAbove(x + 1)을 호출함. + - checkAbove(x)는 이미 x를 방문한 적이 있거나, set 안에 x가 존재하지 않는 경우가 base case + - 따라서 set의 모든 원소를 순회하는 iteration에서, n + a번 호출되므로, 시간 복잡도는 O(n) + - (a는 consecutive chunk의 개수이고 n보다 작거나 같음) + + +Memory: 118.04 MB(Beats: 5.60 %) +Space Complexity: O(n) +- set, vis, cnt : O(n) + */ + +class Solution { + Set set = new HashSet<>(); + Map vis = new HashMap<>(); + Map cnt = new HashMap<>(); // key를 1번째 원소로 하는 연속한 증가 수열의 크기 + + public int longestConsecutive(int[] nums) { + if (nums.length == 0) { + return 0; + } + + for (int num : nums) { + if (set.contains(num)) { + continue; + } + + set.add(num); + vis.put(num, false); + cnt.put(num, 1); + } + + int max = 0; + for (int num : set) { + int cnt = checkAbove(num); + if (max < cnt) { + max = cnt; + } + } + + return max; + } + + public Integer checkAbove(Integer num) { + if (null == vis.get(num)) { + return 0; + } else if (vis.get(num)) { + return cnt.get(num); + } + + vis.put(num, true); + int cntAbove = checkAbove(num + 1); + if (cntAbove > 0) { + cnt.put(num, cntAbove + 1); + } + + return cntAbove + 1; + } +} From a2e083567067b102302908193a38ef11627e8987 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Fri, 13 Dec 2024 23:04:14 +0900 Subject: [PATCH 293/396] feat: house-robber solution --- house-robber/YeomChaeeun.ts | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 house-robber/YeomChaeeun.ts diff --git a/house-robber/YeomChaeeun.ts b/house-robber/YeomChaeeun.ts new file mode 100644 index 000000000..6190fe3b7 --- /dev/null +++ b/house-robber/YeomChaeeun.ts @@ -0,0 +1,43 @@ +/** + * 하나 이상 건너 뛴 값을 더한 것중 가장 높은 값의 합을 구하기 + * @param nums + */ +function rob(nums: number[]): number { + + if(nums.length === 1) return nums[0]; + + // 0 + 2 ... + // 1 + 3 ... + // Max(인덱스 0부터 더한 것, 인덱스 1부터 더한 것) + + // 접근 (1) - 양 옆의 값을 제외하고 홀수/짝수 인덱스 값들을 더했음 + // [2, 1, 1, 2] 일 때, 답이 4가 나와야 함 + // let max = 0 + // let odd = 0 + // let even = 0 + // for(let i = 0; i < nums.length; i++) { + // if(i % 2 == 0) { + // console.log(nums[i], 'even >>>', even); + // even += nums[i]; + // } else { + // console.log(nums[i], 'odd >>>', odd); + // odd += nums[i]; + // } + // } + // console.log(even, '===', odd); + // max = Math.max(even, odd); + + // 접근 (2) - max 값을 저장해두고 Math.max(하나 이상 건너뛴 값 + 현재 값 더한 것, max) 를 구함 + let prev = 0 + let max = 0 + let temp = 0 + for(let i = 0; i < nums.length; i++) { + temp = max + max = Math.max(prev + nums[i], max) // 이전의 값과 하나 이상 건너뛰고 더한 값 중 최대 값을 구함 + prev = temp + + // console.log(temp, " - ", max, " - ", prev) + }; + // console.log(max); + return max; +}; From 19d1243d0ac6fc350e7a1c34413b121771fbfba5 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 23:18:41 +0900 Subject: [PATCH 294/396] =?UTF-8?q?Longest=20Consecutive=20Sequence=20-=20?= =?UTF-8?q?Character=20=EB=A9=94=EC=86=8C=EB=93=9C=20=EC=82=AC=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- valid-palindrome/forest000014.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/valid-palindrome/forest000014.java b/valid-palindrome/forest000014.java index 0a605a9b2..c70a10d0b 100644 --- a/valid-palindrome/forest000014.java +++ b/valid-palindrome/forest000014.java @@ -1,36 +1,34 @@ /* -Runtime: 1 ms(Beats: 100.00 %) +Runtime: 2 ms(Beats: 99.10 %) Time Complexity: O(n) -Memory: 43.00 MB(Beats: 64.54 %) +Memory: 42.75 MB(Beats: 85.31 %) Space Complexity: O(1) ... 문제에서 주어진 String s는 space complexity 계산에서 제외하고, 제가 추가한 변수에 대해서만 계산하면 될까요? + +ps. 처음 풀이에서는 alphanumeric 여부와 대소문자 관련 로직을 일일이 구현했다가, isLetterOrDigit(), toLowerCase()로 변경했습니다. */ class Solution { public boolean isPalindrome(String s) { for (int i = 0, j = s.length() - 1; i < j; i++, j--) { char a = s.charAt(i); - while (a < '0' || (a > '9' && a < 'A') || (a > 'Z' && a < 'a') || a > 'z') { + while (!Character.isLetterOrDigit(a)) { a = s.charAt(++i); if (i >= j) { return true; } } - if (a <= 'Z') { - a += ('a' - 'A'); - } + a = Character.toLowerCase(a); char b = s.charAt(j); - while (b < '0' || (b > '9' && b < 'A') || (b > 'Z' && b < 'a') || b > 'z') { + while (!Character.isLetterOrDigit(b)) { b = s.charAt(--j); if (i >= j) { return true; } } - if (b <= 'Z') { - b += ('a' - 'A'); - } + b = Character.toLowerCase(b); if (a != b) { return false; From e4d71ba974ed53e683c75aa4daa2b91792503ce2 Mon Sep 17 00:00:00 2001 From: forest000014 Date: Fri, 13 Dec 2024 23:42:08 +0900 Subject: [PATCH 295/396] =?UTF-8?q?House=20Robber=20-=20=EA=B3=B5=EA=B0=84?= =?UTF-8?q?=20=EB=B3=B5=EC=9E=A1=EB=8F=84=20=EA=B0=9C=EC=84=A0=20=EB=B0=8F?= =?UTF-8?q?=20=ED=95=B4=EC=84=A4=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- house-robber/forest000014.java | 57 ++++++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 9 deletions(-) diff --git a/house-robber/forest000014.java b/house-robber/forest000014.java index 55bf75368..a498972bf 100644 --- a/house-robber/forest000014.java +++ b/house-robber/forest000014.java @@ -1,14 +1,27 @@ -/* -Runtime: 0 ms(Beats: 100.00 %) -Time Complexity: O(nlogn) -- nums iteration : O(n) +class Solution { + /* + [1, i]의 범위에서 최대값을 구하고자 할 때, 만약 [1, i-1]의 범위에서의 최대값을 이미 계산해 놓았다면 O(1)에 계산할 수 있다는 아이디어에서 출발합니다. + 단, 연속해서 두 집에서 훔칠 수 없다는 전제조건이 있으므로, i-1번째 집에서 훔친 경우와 훔치지 않는 경우 각각에 대한 최대값을 따로 구해두어야 합니다. + dp[i-1][0]에는 i-1번째 집에서 훔치지 않는 경우의 최대값, dp[i-1][1]에는 i-1번째 집에서 훔친 경우의 최대값이 저장되어 있다는 전제하에, + dp[i][0], dp[i][1]을 아래와 같이 구할 수 있습니다. -Memory: 41.40 MB(Beats: 43.05 %) -Space Complexity: O(n) -- dp[n][2] : O(n) * 2 = O(n) -*/ + 1) i번째 집에서 훔치지 않는 경우의 [1, i] 범위에서의 최대값 + i번째 집에서는 훔치지 않을 것이므로, [1, i-1] 범위에서의 최대값이 dp[i][0]이 됩니다. + 단, 여기서 주의할 점은 dp[i-1][1]이 무조건 dp[i-1][0] 이상이라고 착각할 수 있다는 건데요, + {100, 1, 1, 100} 에서 dp[1][0] = 100, dp[1][1] = 1 이라는 케이스를 생각해보면, dp[i-1][0], dp[i-1][1]를 비교해서 큰 것을 선택해야 함을 알 수 있습니다. -class Solution { + 2) i번째 집에서 훔치는 경우의 [1, i] 범위에서의 최대값 + i번째 집에서 훔치기 위해서는, i-1번째 집에서는 훔치지 않았어야만 합니다. + 따라서 단순히 dp[i][1] = dp[i-1][0] + nums[i] 가 됩니다. + + Runtime: 0 ms(Beats: 100.00 %) + Time Complexity: O(n) + - nums iteration : O(n) + + Memory: 41.04 MB(Beats: 43.05 %) + Space Complexity: O(n) + - dp[n][2] : O(n) * 2 = O(n) + */ public int rob(int[] nums) { int[][] dp = new int[nums.length][2]; @@ -20,4 +33,30 @@ public int rob(int[] nums) { return Math.max(dp[nums.length - 1][0], dp[nums.length - 1][1]); } + + /* + 생각해보니 memoization 배열을 굳이 들고다닐 필요가 없어서, + 필요한 값(직전 인덱스에서의 memoization 값)만 저장하도록 수정해서 공간 복잡도를 개선했습니다. + 그런데... 무슨 이유에선지 오히려 메모리 사용량은 더 증가했다고 나오네요...? + + Runtime: 0 ms(Beats: 100.00 %) + Time Complexity: O(n) + - nums iteration : O(n) + + Memory: 41.21 MB(Beats: 22.01 %) + Space Complexity: O(1) + */ + public int rob2(int[] nums) { + int[] dp = new int[2]; + + dp[1] = nums[0]; + for (int i = 1; i < nums.length; i++) { + int tmp0 = Math.max(dp[0], dp[1]); + int tmp1 = dp[0] + nums[i]; + dp[0] = tmp0; + dp[1] = tmp1; + } + + return Math.max(dp[0], dp[1]); + } } From 0df1835df792853f0f29cf48ce134a563731d9b1 Mon Sep 17 00:00:00 2001 From: bus710 Date: Fri, 13 Dec 2024 09:53:14 -0800 Subject: [PATCH 296/396] add a new line --- contains-duplicate/bus710.go | 1 + 1 file changed, 1 insertion(+) diff --git a/contains-duplicate/bus710.go b/contains-duplicate/bus710.go index c0f2179e3..2a2c67338 100644 --- a/contains-duplicate/bus710.go +++ b/contains-duplicate/bus710.go @@ -18,3 +18,4 @@ func containsDuplicate(nums []int) bool { return false } + From 8e56bb8123387c8f0215b0186caa43fdb047e3df Mon Sep 17 00:00:00 2001 From: Dal_Peng Date: Sat, 14 Dec 2024 02:53:53 +0900 Subject: [PATCH 297/396] :art: add time complexity --- contains-duplicate/dalpang81.java | 1 + house-robber/dalpang81.java | 1 + longest-consecutive-sequence/dalpang81.java | 1 + top-k-frequent-elements/dalpang81.java | 1 + valid-palindrome/dalpang81.java | 1 + 5 files changed, 5 insertions(+) diff --git a/contains-duplicate/dalpang81.java b/contains-duplicate/dalpang81.java index dfe3f06a3..2a8269ab3 100644 --- a/contains-duplicate/dalpang81.java +++ b/contains-duplicate/dalpang81.java @@ -1,3 +1,4 @@ +//시간복잡도 : O(nlogn) class Solution { public boolean containsDuplicate(int[] nums) { Arrays.sort(nums); diff --git a/house-robber/dalpang81.java b/house-robber/dalpang81.java index 1220ed06c..e5f76b68a 100644 --- a/house-robber/dalpang81.java +++ b/house-robber/dalpang81.java @@ -1,3 +1,4 @@ +//시간복잡도 O(n) class Solution { public int rob(int[] nums) { if (nums.length == 1) { diff --git a/longest-consecutive-sequence/dalpang81.java b/longest-consecutive-sequence/dalpang81.java index 5ef58b501..d5cfa414f 100644 --- a/longest-consecutive-sequence/dalpang81.java +++ b/longest-consecutive-sequence/dalpang81.java @@ -1,3 +1,4 @@ +//시간복잡도: O(n) import java.util.*; class Solution { diff --git a/top-k-frequent-elements/dalpang81.java b/top-k-frequent-elements/dalpang81.java index 119626f92..569869398 100644 --- a/top-k-frequent-elements/dalpang81.java +++ b/top-k-frequent-elements/dalpang81.java @@ -1,3 +1,4 @@ +//시간복잡도: O(n + mlogk) import java.util.*; class Solution { public int[] topKFrequent(int[] nums, int k) { diff --git a/valid-palindrome/dalpang81.java b/valid-palindrome/dalpang81.java index 465a3219a..c2ef2bbea 100644 --- a/valid-palindrome/dalpang81.java +++ b/valid-palindrome/dalpang81.java @@ -1,3 +1,4 @@ +//시간복잡도: O(n) class Solution { public boolean isPalindrome(String s) { s = s.toLowerCase().trim(); From 658e7452489720723e7a77ade648f6f5d23af118 Mon Sep 17 00:00:00 2001 From: Paik Date: Sun, 8 Dec 2024 17:02:47 +0900 Subject: [PATCH 298/396] feat: 217.Contains Duplicate --- contains-duplicate/ganu.js | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 contains-duplicate/ganu.js diff --git a/contains-duplicate/ganu.js b/contains-duplicate/ganu.js new file mode 100644 index 000000000..deeb8c753 --- /dev/null +++ b/contains-duplicate/ganu.js @@ -0,0 +1,12 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function (nums) { + const set = new Set(nums); + + return set.size !== nums.length; +}; From ac171d765858c9851ba98cf9075b6154762d4e79 Mon Sep 17 00:00:00 2001 From: Paik Date: Sun, 8 Dec 2024 17:15:06 +0900 Subject: [PATCH 299/396] fix: Change file name --- contains-duplicate/{ganu.js => gwbaik9717.js} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{ganu.js => gwbaik9717.js} (100%) diff --git a/contains-duplicate/ganu.js b/contains-duplicate/gwbaik9717.js similarity index 100% rename from contains-duplicate/ganu.js rename to contains-duplicate/gwbaik9717.js From a23fadd0c74837ee42a36415889fae25c7180840 Mon Sep 17 00:00:00 2001 From: Paik Date: Mon, 9 Dec 2024 11:26:59 +0900 Subject: [PATCH 300/396] feat: 220.Valid Palindrome --- valid-palindrome/gwbaik9717.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 valid-palindrome/gwbaik9717.js diff --git a/valid-palindrome/gwbaik9717.js b/valid-palindrome/gwbaik9717.js new file mode 100644 index 000000000..890929a89 --- /dev/null +++ b/valid-palindrome/gwbaik9717.js @@ -0,0 +1,17 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function (s) { + const normalize = (s) => { + return s.toLowerCase().replace(/[^a-z0-9]/g, ""); + }; + + const normalized = normalize(s); + const reversed = normalized.split("").reverse().join(""); + + return normalized === reversed; +}; From 765ba5af83ad9e088a20ee8e5729123976910465 Mon Sep 17 00:00:00 2001 From: Paik Date: Tue, 10 Dec 2024 08:12:22 +0900 Subject: [PATCH 301/396] feat: 347. Top K Frequent Elements --- top-k-frequent-elements/gwbaik9717.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 top-k-frequent-elements/gwbaik9717.js diff --git a/top-k-frequent-elements/gwbaik9717.js b/top-k-frequent-elements/gwbaik9717.js new file mode 100644 index 000000000..a539d1198 --- /dev/null +++ b/top-k-frequent-elements/gwbaik9717.js @@ -0,0 +1,24 @@ +// Time complexity: O(nlogn) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function (nums, k) { + const frequencyDict = new Map(); + + for (const num of nums) { + if (frequencyDict.has(num)) { + frequencyDict.set(num, frequencyDict.get(num) + 1); + } else { + frequencyDict.set(num, 1); + } + } + + const entries = [...frequencyDict.entries()]; + entries.sort((a, b) => b[1] - a[1]); + + return entries.slice(0, k).map((entry) => entry[0]); +}; From df69e0ef60f442d53cea4a5ed49b7687829228b9 Mon Sep 17 00:00:00 2001 From: Paik Date: Wed, 11 Dec 2024 09:15:55 +0900 Subject: [PATCH 302/396] feat: 128. Longest Consecutive Sequence --- longest-consecutive-sequence/gwbaik9717.js | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 longest-consecutive-sequence/gwbaik9717.js diff --git a/longest-consecutive-sequence/gwbaik9717.js b/longest-consecutive-sequence/gwbaik9717.js new file mode 100644 index 000000000..0835fba7e --- /dev/null +++ b/longest-consecutive-sequence/gwbaik9717.js @@ -0,0 +1,30 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + let answer = 0; + const consecutiveDict = new Map(); + + for (const num of nums) { + consecutiveDict.set(num, true); + } + + for (const num of nums) { + if (consecutiveDict.has(num - 1)) { + continue; + } + + let length = 1; + while (consecutiveDict.has(num + length)) { + length++; + } + + answer = Math.max(answer, length); + } + + return answer; +}; From 3da7d435d4acbd03326b28d02c5fb99fb7b87272 Mon Sep 17 00:00:00 2001 From: Paik Date: Thu, 12 Dec 2024 07:59:54 +0900 Subject: [PATCH 303/396] feat: 198. House Robber --- house-robber/gwbaik9717.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 house-robber/gwbaik9717.js diff --git a/house-robber/gwbaik9717.js b/house-robber/gwbaik9717.js new file mode 100644 index 000000000..e54c9c2e9 --- /dev/null +++ b/house-robber/gwbaik9717.js @@ -0,0 +1,18 @@ +// Time complexity: O(n) +// Space complexity: O(n) + +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function (nums) { + const n = nums.length; + const dp = Array.from({ length: n + 1 }, () => 0); + dp[1] = nums[0]; + + for (let i = 2; i < n + 1; i++) { + dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]); + } + + return dp.at(-1); +}; From 3acda42a89f1169a4cb0e2883df70ac2e980d255 Mon Sep 17 00:00:00 2001 From: Gunwoo Baik Date: Fri, 13 Dec 2024 06:32:37 +0900 Subject: [PATCH 304/396] refactor: Remove unnecessary function Co-authored-by: Dongyeong Chon --- valid-palindrome/gwbaik9717.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/valid-palindrome/gwbaik9717.js b/valid-palindrome/gwbaik9717.js index 890929a89..4e2ac5871 100644 --- a/valid-palindrome/gwbaik9717.js +++ b/valid-palindrome/gwbaik9717.js @@ -6,11 +6,7 @@ * @return {boolean} */ var isPalindrome = function (s) { - const normalize = (s) => { - return s.toLowerCase().replace(/[^a-z0-9]/g, ""); - }; - - const normalized = normalize(s); + const normalized = s.toLowerCase().replace(/[^a-z0-9]/g, ""); const reversed = normalized.split("").reverse().join(""); return normalized === reversed; From 63dac45956a5f1661c09549f8c26b1a6968288e2 Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Fri, 13 Dec 2024 10:06:51 -0800 Subject: [PATCH 305/396] contains duplicate solution --- contains-duplicate/EstherKim97.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 contains-duplicate/EstherKim97.py diff --git a/contains-duplicate/EstherKim97.py b/contains-duplicate/EstherKim97.py new file mode 100644 index 000000000..60dad6f0c --- /dev/null +++ b/contains-duplicate/EstherKim97.py @@ -0,0 +1,9 @@ +# Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. + +def containsDuplicate(nums): + seen = set() + for num in nums: + if num in seen: + return True + seen.add(num) + return False \ No newline at end of file From dc6b6ad49c0b603802b5a6dea855f10469cc0538 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 13 Dec 2024 17:18:44 -0500 Subject: [PATCH 306/396] Solve: topKFrequent --- top-k-frequent-elements/Jay-Mo-99.py | 43 ++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 top-k-frequent-elements/Jay-Mo-99.py diff --git a/top-k-frequent-elements/Jay-Mo-99.py b/top-k-frequent-elements/Jay-Mo-99.py new file mode 100644 index 000000000..87434cb26 --- /dev/null +++ b/top-k-frequent-elements/Jay-Mo-99.py @@ -0,0 +1,43 @@ + #해석 + #nums를 dictionary로 전환한다. nums의 기존 element가 key, element의 갯수를 value값으로 지정한다. + #value값이 큰 순서대로 dictionary의 요소를 정렬한다 + #그중 0에서 k-1까지의 key값만을 반환한다. + + #Big O + #N: 주어진 list의 길이 nums (Length of the input list nums) + #M: count 딕셔너리의 고유한 key 의 갯수 + + #Time Complexity: O(NLogN) + #- count: N의 길이에 기반하여 생성된다 : O(N) + #- sorted_count: 파이썬의 sorted 메소드는 Timesort 알고리즘 기반의 비교 기반 정렬 알고리즘 + # 리스트의 길이가 M이면 sorted()는 요소들을 쪼개고 병합하여 정렬한다. 대략 M개의 요소를 logM번 비교 + + #Space Complexity: O(N) + #- count: M개에 기반하여 Dictionary 공간 저장: O(M) + #- sorted_count: count.items의 갯수에 기반하여 공간 저장 : O(M) + #- dic_count: 상위 요소 갯수(k개) 만큼 저장 : O(k) + #- 최종: O(N) + O(M) + O(k): k는 최대 M개 만큼 가능하고 M은 최대 N개만큼 가능하다. + +class Solution(object): + def topKFrequent(self, nums, k): + """ + :type nums: List[int] + :type k: int + :rtype: List[int] + """ + + #Create dictionary which have a key(element of nums) and value(count num of the element) + count = {} + for i in nums: + try: count[i] += 1 + except: count[i] = 1 + + #Sort depends on the value descending order + sorted_count = sorted(count.items(),key=lambda x:x[1],reverse=True) + #k까지의 요소만을 dictionary data type으로 convert + dic_count = dict(sorted_count[:k]) + #Return keys + return dic_count.keys() + + + From a560bdd43ddd75cd78d60350b2ad31118b25769d Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 13 Dec 2024 20:46:19 -0500 Subject: [PATCH 307/396] Solve: Longest Consecutive Sequence --- longest-consecutive-sequence/Jay-Mo-99.py | 49 +++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 longest-consecutive-sequence/Jay-Mo-99.py diff --git a/longest-consecutive-sequence/Jay-Mo-99.py b/longest-consecutive-sequence/Jay-Mo-99.py new file mode 100644 index 000000000..bba6db868 --- /dev/null +++ b/longest-consecutive-sequence/Jay-Mo-99.py @@ -0,0 +1,49 @@ +# --- 해석 --- +#매개변수 nums 를 set으로 바꿔서 중복제거 +#set을 list로 전환하여 sort하여 오름차순으로 변환 +#for loop 로 nums[1]부터 nums[len(nums)-1] 에 접근 +#nums[i]-nums[i-1] =1 이면 변수 current를 증가, longest는 current의 최댓값을 업데이트 +#만약 해당 조건을 만족하지 않는다면 current를 1로 초기화, 이후 longest 값 return + +# --- Big O +#N: 매개변수 nums의 길이가 N이다. + +# Time Complexity: O(N) +#- set(nums)는 nums의모든 요소를 하나씩 순회하며 중복 제거 : O(N) +#- list(set(nums)) 는 data type을 변환하면서 nums의 갯수만큼 data를 추가 생성: O(N) +#- for loop 는 nums[1] 부터 nums[len(nums)-1]만큼 순회: O(N) + +# Space Complexity: O(N) +#-nums = list(set(nums)): list(),set(),dict() 이런 data type을 변환할때마다 N만큼 공간 추가할당: O(N) +#-longest,current 변수는 상수 : O(1) + +class Solution(object): + def longestConsecutive(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + #If the nums doesn't have elements, return 0 + if len(nums) ==0: + return 0 + #중복제거 set + nums = list(set(nums)) + #sort + nums.sort() + print(nums) + + #Variables + longest = 1 + current = 1 + + #Approah all element of nums for checking the sequnece number or not + for i in range(1,len(nums)): + if nums[i] == nums[i-1] + 1: + current +=1 #current는 nums[i]와 nums[i-1]의 차이가 1이면 +1해줌. + longest = max(longest, current) #return값을 위해 currrent가 가장 크도록 업데이트 + else:#연속 되지 않을 시 current 1로 초기화 + current =1 + print(longest) + return longest + + From 19f620541d62578274a19553a3fea918ce808374 Mon Sep 17 00:00:00 2001 From: hancrysta1 Date: Sat, 14 Dec 2024 11:05:29 +0900 Subject: [PATCH 308/396] contains-duplicate solution --- contains-duplicate/sj.java | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 contains-duplicate/sj.java diff --git a/contains-duplicate/sj.java b/contains-duplicate/sj.java new file mode 100644 index 000000000..b0838e3f0 --- /dev/null +++ b/contains-duplicate/sj.java @@ -0,0 +1,8 @@ +import java.util.*; +class Solution { + public boolean containsDuplicate(int[] nums) { + Set numSet = Arrays.stream(nums).boxed().collect(Collectors.toSet()); + if(numSet.size()!=nums.length) return true; + else return false; + } +} \ No newline at end of file From b61d5b06a65ed74c41e306f8fc6a6cead4c7990a Mon Sep 17 00:00:00 2001 From: jonghun Date: Sat, 14 Dec 2024 11:11:51 +0900 Subject: [PATCH 309/396] add solution containsDuplicate --- contains-duplicate/JonghunLee.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 contains-duplicate/JonghunLee.py diff --git a/contains-duplicate/JonghunLee.py b/contains-duplicate/JonghunLee.py new file mode 100644 index 000000000..ecd4489fc --- /dev/null +++ b/contains-duplicate/JonghunLee.py @@ -0,0 +1,27 @@ + +# Time complexity: O(n) +# The process of traversing a list to generate a set is proportional to the length of the input list. +# Space complexity: O(n) +# The size of the set for storing deduplicated elements is proportional to the length of the input list. + +class Solution: + def containsDuplicate(self, nums: list[int]) -> bool: + list_len = len(nums) + set_len = len(set(nums)) + + return list_len != set_len + +if __name__ == "__main__": + solution = Solution() + + # test case + test_string = [ + [1,2,3,1], # True + [1,2,3,4], # False + [1,1,1,3,3,4,3,2,4,2], # True + ] + + for index, test in enumerate(test_string): + print(f"start {index} test") + print(f"input : {test}") + print(f"Is valid palindrome ? {solution.containsDuplicate(test)}\n") From 80a4899df0c520d6a25a5ee2ea843b34c193e667 Mon Sep 17 00:00:00 2001 From: jonghun Date: Sat, 14 Dec 2024 11:12:08 +0900 Subject: [PATCH 310/396] add solution valid palindrome --- valid-palindrome/JonghunLee.py | 51 ++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 valid-palindrome/JonghunLee.py diff --git a/valid-palindrome/JonghunLee.py b/valid-palindrome/JonghunLee.py new file mode 100644 index 000000000..5a3cd64a8 --- /dev/null +++ b/valid-palindrome/JonghunLee.py @@ -0,0 +1,51 @@ +import re + + +# Time Complexity O(n) +# - Both normal preprocessing and two-pointer comparisons have time complexity proportional to the length of the input string. +# Space Complexity O(n) +# - The space of the new string joined_string preprocessed from the input string is proportional to the length of the input string. + +class Solution: + def isPalindrome(self, s: str) -> bool: + # Pre-processing using regular expression + joined_string = re.sub(r"[^a-zA-Z]", "", s.lower()) + str_length = len(joined_string) + + + # for loop n/2, two pointer for verify same or not + for i in range(str_length // 2): + end = str_length - i - 1 + if not self.check_palindrome(i, end, joined_string): + return False + + return True + + def check_palindrome(self, i, end, joined_string) -> bool: + left = joined_string[i] + right = joined_string[end] + + if left == right: + return True + else: + return False + +if __name__ == "__main__": + solution = Solution() + + # test case + test_string = [ + "A man, a plan, a canal: Panama", # True (회문) + "race a car", # False (회문 아님) + " ", # True (빈 문자열도 회문으로 간주) + "abba", # True (회문) + "abcba", # True (회문) + ] + + for index, test in enumerate(test_string): + print(f"start {index} test") + print(f"input : {test}") + print(f"Is valid palindrome ? {solution.isPalindrome(test)}\n") + + + From 3dc6420e3d2758b3d823cd18afffdaf0f50a61f3 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 13 Dec 2024 21:16:06 -0500 Subject: [PATCH 311/396] Solve: House Robber --- house-robber/Jay-Mo-99.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 house-robber/Jay-Mo-99.py diff --git a/house-robber/Jay-Mo-99.py b/house-robber/Jay-Mo-99.py new file mode 100644 index 000000000..4d4021e23 --- /dev/null +++ b/house-robber/Jay-Mo-99.py @@ -0,0 +1,37 @@ +# --- 해석 --- +#매개변수 nums 를 순회하면서 nums[i] 일때의 최대 누적값을 업데이트 한다 +#prev1은 현재까지의 최고 누적금액, prev2는 이전 집까지의 최고 누적금액이다. +#현재 집 nums[i] 를 도둑질 하려면, 이전 집까지의 최고금액(prev2) + 현재 집(nums[i])이다. +#현재 집 nums[i]를 도둑질에 제외하려면 현재까지의 최고 금엑(prev1) 이다. +#loop 당 저 둘의 최댓값을 선택하여 current변수에 update해준다. + +# --- Big O +#N: 매개변수 nums의 길이가 N이다. + +# Time Complexity: O(N) +#- for loop 는 nums[0] 부터 nums[len(nums)]만큼 순회: O(N) + +# Space Complexity: O(1) +#-current,prev1,prev2 는 nums와 무관한 상수 메로리 할당: O(1) + + +class Solution(object): + def rob(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + #prev1: 현재 집까지의 최고 금액 + #prev2: 이이전 집까지의 최고 금액 + prev1,prev2=0,0 + + for num in nums: + #current는 prev1과 prev2+num 중 큰 값을 update + current = max(prev1,prev2+num) + prev2 = prev1 #current업데이트 이후 prev1(현재 최고금액) 이 prev2(이어진 집까지 최고금액)가된다 + prev1= current #prev1은 현 num까지 고려된 current의 값이다. (현재 최고 금액액) + return prev1 +nums = [2,7,9,3,1] +solution = Solution() +solution.rob(nums) + From 4bf599c0c3bbd1e11773c4221051c11c5923b275 Mon Sep 17 00:00:00 2001 From: hancrysta1 Date: Sat, 14 Dec 2024 11:27:27 +0900 Subject: [PATCH 312/396] valid-palindrome solution --- valid-palindrome/sj.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 valid-palindrome/sj.java diff --git a/valid-palindrome/sj.java b/valid-palindrome/sj.java new file mode 100644 index 000000000..96012eab1 --- /dev/null +++ b/valid-palindrome/sj.java @@ -0,0 +1,18 @@ +import java.util.*; +class Solution { + public boolean isPalindrome(String s) { + String words = s.toLowerCase().replaceAll("[^0-9A-Za-z]",""); + //System.out.println(words); + Deque stack = new ArrayDeque<>(); + for(int i=0;i Date: Sat, 14 Dec 2024 11:28:33 +0900 Subject: [PATCH 313/396] top-k-frequent-elements solution --- top-k-frequent-elements/sj.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 top-k-frequent-elements/sj.java diff --git a/top-k-frequent-elements/sj.java b/top-k-frequent-elements/sj.java new file mode 100644 index 000000000..0fba33de1 --- /dev/null +++ b/top-k-frequent-elements/sj.java @@ -0,0 +1,17 @@ +import java.util.*; +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map count = new HashMap<>(); + for(int i=0;i sortedCount = new ArrayList<>(count.keySet()); + sortedCount.sort((a,b)->count.get(b)-count.get(a));//value 기준 키 정렬 + int[] answer = new int[k]; + for(int i=0;i Date: Sat, 14 Dec 2024 13:34:45 +0900 Subject: [PATCH 314/396] Feat: Add solution of house-robber --- house-robber/easyone-jwlee.go | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 house-robber/easyone-jwlee.go diff --git a/house-robber/easyone-jwlee.go b/house-robber/easyone-jwlee.go new file mode 100644 index 000000000..863974e02 --- /dev/null +++ b/house-robber/easyone-jwlee.go @@ -0,0 +1,36 @@ +// 풀이 +// dp를 사용하여 현재 털 수 있는 최대한의 돈을 계산 +// curr이 prev가 되고, prev였던 값이 새로운 값을 더한 것과 curr 이었던 값의 최대값을 비교한 것이 새로운 curr이 된다. +// 마지막엔 prev와 curr의 최대값을 비교 +// 이렇게 하면 털 수 있는 집의 최대값을 계속 가지고 있을 수 있게 됨. + +// TC +// O(n) + +// SC +// 늘어나지 않는 int 값만 사용했으므로 O(1) + +func rob(nums []int) int { + length := len(nums) + + if length == 1 { + return nums[0] + } + + prev := 0 + curr := nums[0] + + for i := 1; i < length; i++ { + prev, curr = curr, max(nums[i]+prev, curr) + } + + return max(prev, curr) +} + +func max(a, b int) int { + if a > b { + return a + } else { + return b + } +} From e884ecdb1fd96f6b05817c2a64c9cb5f146034dc Mon Sep 17 00:00:00 2001 From: dongha kim Date: Sat, 14 Dec 2024 13:40:47 +0900 Subject: [PATCH 315/396] feat : week01 --- contains-duplicate/ackku.java | 15 +++++ house-robber/ackku.java | 33 +++++++++++ longest-consecutive-sequence/ackku.java | 79 +++++++++++++++++++++++++ top-k-frequent-elements/ackku.java | 20 +++++++ valid-palindrome/ackku.java | 20 +++++++ 5 files changed, 167 insertions(+) create mode 100644 contains-duplicate/ackku.java create mode 100644 house-robber/ackku.java create mode 100644 longest-consecutive-sequence/ackku.java create mode 100644 top-k-frequent-elements/ackku.java create mode 100644 valid-palindrome/ackku.java diff --git a/contains-duplicate/ackku.java b/contains-duplicate/ackku.java new file mode 100644 index 000000000..eea277ccf --- /dev/null +++ b/contains-duplicate/ackku.java @@ -0,0 +1,15 @@ +// 중복제거를 위해 set을 적극적으로 활용해야할 듯... +class Solution { + public boolean containsDuplicate(int[] nums) { + Set numSet = new HashSet<>(); + + for (int num : nums) { + if (numSet.contains(num)) { + return true; + } + numSet.add(num); + } + + return false; + } +} diff --git a/house-robber/ackku.java b/house-robber/ackku.java new file mode 100644 index 000000000..9c3dac7c2 --- /dev/null +++ b/house-robber/ackku.java @@ -0,0 +1,33 @@ +// 공간복잡도를 줄이는법. 배열로 관리 안하기 +class Solution { + public int rob(int[] nums) { + if (nums.length == 1) return nums[0]; + + int prev2 = nums[0]; // dp[i-2] + int prev1 = Math.max(nums[0], nums[1]); // dp[i-1] + for (int i = 2; i < nums.length; i++) { + int current = Math.max(nums[i] + prev2, prev1); + prev2 = prev1; + prev1 = current; + } + return prev1; + } +} + +class Solution { + public int rob(int[] nums) { + // 점화식의 최대값을 구하는 방법 + // 1. 현재 위치의 최대 값은 한칸 전 집까지만 털었던가(두칸 연속 겹치면 안된다는 룰을 지키면서) + // 2. 두칸 전 집까지 털고 + 현재집을 털었을 때다 + if (nums.length == 1) { + return nums[0]; + } + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + for (int i = 2; i < nums.length; i++) { + dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]); + } + return dp[nums.length - 1]; + } +} diff --git a/longest-consecutive-sequence/ackku.java b/longest-consecutive-sequence/ackku.java new file mode 100644 index 000000000..e9a2d540b --- /dev/null +++ b/longest-consecutive-sequence/ackku.java @@ -0,0 +1,79 @@ +// 중복여부만 제거하고 포함여부로 판단 O(N) +class Solution { + public int longestConsecutive(int[] nums) { + if (nums == null || nums.length == 0) { + return 0; + } + + HashSet set = new HashSet<>(); + for (int num : nums) { + set.add(num); + } + + int maxLength = 0; + + for (int num : set) { + if (!set.contains(num - 1)) { + int currentNum = num; + int count = 1; + while (set.contains(currentNum + 1)) { + currentNum++; + count++; + } + + maxLength = Math.max(maxLength, count); + } + } + + return maxLength; + } +} +// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 +class Solution { + public int longestConsecutive(int[] nums) { + if(nums.length == 0) return 0; + TreeSet set = new TreeSet<>(); + for (int num : nums) { + set.add(num); + } + int max = 1; + int consecutiveCount = 1; + int prev = set.pollFirst(); + while(!set.isEmpty()) { + int next = set.pollFirst(); + if (next - prev == 1) { + consecutiveCount++; + } else { + max = Math.max(consecutiveCount, max); + consecutiveCount = 1; + } + prev = next; + } + return Math.max(max, consecutiveCount); + } +} +// 이중 변환 필요 없음 +class Solution { + public int longestConsecutive(int[] nums) { + if(nums.length == 0) return 0; + HashSet set = new HashSet<>(); + for (int num : nums) { + set.add(num); + } + PriorityQueue pq = new PriorityQueue<>(set); + int max = 1; + int consecutiveCount = 1; + int prev = pq.poll(); + while(!pq.isEmpty()) { + int next = pq.poll(); + if (next - prev == 1) { + consecutiveCount++; + } else { + max = Math.max(consecutiveCount, max); + consecutiveCount = 1; + } + prev = next; + } + return Math.max(max, consecutiveCount); + } +} diff --git a/top-k-frequent-elements/ackku.java b/top-k-frequent-elements/ackku.java new file mode 100644 index 000000000..a7a6cde03 --- /dev/null +++ b/top-k-frequent-elements/ackku.java @@ -0,0 +1,20 @@ +class Solution { + public int[] topKFrequent(int[] nums, int k) { + Map countMap = new HashMap<>(); + for (int num : nums) { + countMap.put(num, countMap.getOrDefault(num, 0) + 1); + } + + PriorityQueue pq = new PriorityQueue<>( + Comparator.comparingInt(countMap::get).reversed() + ); + + pq.addAll(countMap.keySet()); + + int[] result = new int[k]; + for (int i = 0; i < k; i++) { + result[i] = pq.poll(); + } + return result; + } +} diff --git a/valid-palindrome/ackku.java b/valid-palindrome/ackku.java new file mode 100644 index 000000000..66c39318e --- /dev/null +++ b/valid-palindrome/ackku.java @@ -0,0 +1,20 @@ +// 정규표현식으로 풀기엔 재미없어보여서 Character.isLetterOrDigit을 이용함 +class Solution { + public boolean isPalindrome(String s) { + int left = 0 + int right = s.length() - 1; + + while (left < right) { + 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; + } +} From e811d2d16f33d0599a7918de48cc0b1a767d3137 Mon Sep 17 00:00:00 2001 From: dongha kim Date: Sat, 14 Dec 2024 13:59:01 +0900 Subject: [PATCH 316/396] =?UTF-8?q?fix=20:=20=EC=86=94=EB=A3=A8=EC=85=98?= =?UTF-8?q?=20=ED=95=98=EB=82=98=EB=A7=8C=20=EB=82=A8=EA=B8=B0=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- house-robber/ackku.java | 21 ++-------- longest-consecutive-sequence/ackku.java | 51 +------------------------ 2 files changed, 5 insertions(+), 67 deletions(-) diff --git a/house-robber/ackku.java b/house-robber/ackku.java index 9c3dac7c2..488f282df 100644 --- a/house-robber/ackku.java +++ b/house-robber/ackku.java @@ -1,3 +1,6 @@ +// 점화식의 최대값을 구하는 방법 +// 1. 현재 위치의 최대 값은 한칸 전 집까지만 털었던가(두칸 연속 겹치면 안된다는 룰을 지키면서) +// 2. 두칸 전 집까지 털고 + 현재집을 털었을 때다 // 공간복잡도를 줄이는법. 배열로 관리 안하기 class Solution { public int rob(int[] nums) { @@ -13,21 +16,3 @@ public int rob(int[] nums) { return prev1; } } - -class Solution { - public int rob(int[] nums) { - // 점화식의 최대값을 구하는 방법 - // 1. 현재 위치의 최대 값은 한칸 전 집까지만 털었던가(두칸 연속 겹치면 안된다는 룰을 지키면서) - // 2. 두칸 전 집까지 털고 + 현재집을 털었을 때다 - if (nums.length == 1) { - return nums[0]; - } - int[] dp = new int[nums.length]; - dp[0] = nums[0]; - dp[1] = Math.max(nums[0], nums[1]); - for (int i = 2; i < nums.length; i++) { - dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]); - } - return dp[nums.length - 1]; - } -} diff --git a/longest-consecutive-sequence/ackku.java b/longest-consecutive-sequence/ackku.java index e9a2d540b..c59da0b98 100644 --- a/longest-consecutive-sequence/ackku.java +++ b/longest-consecutive-sequence/ackku.java @@ -1,3 +1,5 @@ +// 이중 변환 필요 없음 +// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 // 중복여부만 제거하고 포함여부로 판단 O(N) class Solution { public int longestConsecutive(int[] nums) { @@ -28,52 +30,3 @@ public int longestConsecutive(int[] nums) { return maxLength; } } -// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 -class Solution { - public int longestConsecutive(int[] nums) { - if(nums.length == 0) return 0; - TreeSet set = new TreeSet<>(); - for (int num : nums) { - set.add(num); - } - int max = 1; - int consecutiveCount = 1; - int prev = set.pollFirst(); - while(!set.isEmpty()) { - int next = set.pollFirst(); - if (next - prev == 1) { - consecutiveCount++; - } else { - max = Math.max(consecutiveCount, max); - consecutiveCount = 1; - } - prev = next; - } - return Math.max(max, consecutiveCount); - } -} -// 이중 변환 필요 없음 -class Solution { - public int longestConsecutive(int[] nums) { - if(nums.length == 0) return 0; - HashSet set = new HashSet<>(); - for (int num : nums) { - set.add(num); - } - PriorityQueue pq = new PriorityQueue<>(set); - int max = 1; - int consecutiveCount = 1; - int prev = pq.poll(); - while(!pq.isEmpty()) { - int next = pq.poll(); - if (next - prev == 1) { - consecutiveCount++; - } else { - max = Math.max(consecutiveCount, max); - consecutiveCount = 1; - } - prev = next; - } - return Math.max(max, consecutiveCount); - } -} From 495b9d2d087e5e9428dccae3a07d14924149c156 Mon Sep 17 00:00:00 2001 From: dongha kim Date: Sat, 14 Dec 2024 14:04:39 +0900 Subject: [PATCH 317/396] =?UTF-8?q?fix=20:=20=ED=8C=8C=EC=9D=BC=EB=AA=85?= =?UTF-8?q?=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/{ackku.java => imsosleepy.java} | 0 house-robber/{ackku.java => imsosleepy.java} | 0 longest-consecutive-sequence/{ackku.java => imsosleepy.java} | 0 top-k-frequent-elements/{ackku.java => imsosleepy.java} | 0 valid-palindrome/{ackku.java => imsosleepy.java} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{ackku.java => imsosleepy.java} (100%) rename house-robber/{ackku.java => imsosleepy.java} (100%) rename longest-consecutive-sequence/{ackku.java => imsosleepy.java} (100%) rename top-k-frequent-elements/{ackku.java => imsosleepy.java} (100%) rename valid-palindrome/{ackku.java => imsosleepy.java} (100%) diff --git a/contains-duplicate/ackku.java b/contains-duplicate/imsosleepy.java similarity index 100% rename from contains-duplicate/ackku.java rename to contains-duplicate/imsosleepy.java diff --git a/house-robber/ackku.java b/house-robber/imsosleepy.java similarity index 100% rename from house-robber/ackku.java rename to house-robber/imsosleepy.java diff --git a/longest-consecutive-sequence/ackku.java b/longest-consecutive-sequence/imsosleepy.java similarity index 100% rename from longest-consecutive-sequence/ackku.java rename to longest-consecutive-sequence/imsosleepy.java diff --git a/top-k-frequent-elements/ackku.java b/top-k-frequent-elements/imsosleepy.java similarity index 100% rename from top-k-frequent-elements/ackku.java rename to top-k-frequent-elements/imsosleepy.java diff --git a/valid-palindrome/ackku.java b/valid-palindrome/imsosleepy.java similarity index 100% rename from valid-palindrome/ackku.java rename to valid-palindrome/imsosleepy.java From db5c31411272b4a7140842d11ee79f5560dbe328 Mon Sep 17 00:00:00 2001 From: dongha kim Date: Sat, 14 Dec 2024 14:08:01 +0900 Subject: [PATCH 318/396] =?UTF-8?q?fix=20:=20=EC=BD=94=EB=93=9C=20?= =?UTF-8?q?=EC=9B=90=EB=B3=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- house-robber/imsosleepy.java | 21 ++++++-- longest-consecutive-sequence/imsosleepy.java | 51 +++++++++++++++++++- 2 files changed, 67 insertions(+), 5 deletions(-) diff --git a/house-robber/imsosleepy.java b/house-robber/imsosleepy.java index 488f282df..aaff2084e 100644 --- a/house-robber/imsosleepy.java +++ b/house-robber/imsosleepy.java @@ -1,6 +1,3 @@ -// 점화식의 최대값을 구하는 방법 -// 1. 현재 위치의 최대 값은 한칸 전 집까지만 털었던가(두칸 연속 겹치면 안된다는 룰을 지키면서) -// 2. 두칸 전 집까지 털고 + 현재집을 털었을 때다 // 공간복잡도를 줄이는법. 배열로 관리 안하기 class Solution { public int rob(int[] nums) { @@ -16,3 +13,21 @@ public int rob(int[] nums) { return prev1; } } + +// 점화식의 최대값을 구하는 방법 +// 1. 현재 위치의 최대 값은 한칸 전 집까지만 털었던가(두칸 연속 겹치면 안된다는 룰을 지키면서) +// 2. 두칸 전 집까지 털고 + 현재집을 털었을 때다 +class Solution { + public int rob(int[] nums) { + if (nums.length == 1) { + return nums[0]; + } + int[] dp = new int[nums.length]; + dp[0] = nums[0]; + dp[1] = Math.max(nums[0], nums[1]); + for (int i = 2; i < nums.length; i++) { + dp[i] = Math.max(nums[i] + dp[i - 2], dp[i - 1]); + } + return dp[nums.length - 1]; + } +} diff --git a/longest-consecutive-sequence/imsosleepy.java b/longest-consecutive-sequence/imsosleepy.java index c59da0b98..e9a2d540b 100644 --- a/longest-consecutive-sequence/imsosleepy.java +++ b/longest-consecutive-sequence/imsosleepy.java @@ -1,5 +1,3 @@ -// 이중 변환 필요 없음 -// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 // 중복여부만 제거하고 포함여부로 판단 O(N) class Solution { public int longestConsecutive(int[] nums) { @@ -30,3 +28,52 @@ public int longestConsecutive(int[] nums) { return maxLength; } } +// 정렬이 들어가면 O(nlogn) 아래로 줄일 수 없음 +class Solution { + public int longestConsecutive(int[] nums) { + if(nums.length == 0) return 0; + TreeSet set = new TreeSet<>(); + for (int num : nums) { + set.add(num); + } + int max = 1; + int consecutiveCount = 1; + int prev = set.pollFirst(); + while(!set.isEmpty()) { + int next = set.pollFirst(); + if (next - prev == 1) { + consecutiveCount++; + } else { + max = Math.max(consecutiveCount, max); + consecutiveCount = 1; + } + prev = next; + } + return Math.max(max, consecutiveCount); + } +} +// 이중 변환 필요 없음 +class Solution { + public int longestConsecutive(int[] nums) { + if(nums.length == 0) return 0; + HashSet set = new HashSet<>(); + for (int num : nums) { + set.add(num); + } + PriorityQueue pq = new PriorityQueue<>(set); + int max = 1; + int consecutiveCount = 1; + int prev = pq.poll(); + while(!pq.isEmpty()) { + int next = pq.poll(); + if (next - prev == 1) { + consecutiveCount++; + } else { + max = Math.max(consecutiveCount, max); + consecutiveCount = 1; + } + prev = next; + } + return Math.max(max, consecutiveCount); + } +} From fdbee2cd4851aed6e226b817017de5b89b5de146 Mon Sep 17 00:00:00 2001 From: jonghun Date: Sat, 14 Dec 2024 14:53:22 +0900 Subject: [PATCH 319/396] add solution top k frequent elements --- top-k-frequent-elements/JonghunLee.py | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 top-k-frequent-elements/JonghunLee.py diff --git a/top-k-frequent-elements/JonghunLee.py b/top-k-frequent-elements/JonghunLee.py new file mode 100644 index 000000000..4dc1f9705 --- /dev/null +++ b/top-k-frequent-elements/JonghunLee.py @@ -0,0 +1,41 @@ +from typing import List + +# Time Complexity O(n log n) +# - traversing for loop takes O(n) to create hash dictionary, +# - and when sorting by sorted function(TimSort) it takes O(nlogn) +# Space Complexity O(n log n) +# - creating hash dictionary takes O(n) +# - and when sorting takes O(n), hash[x] occupy O(1) + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + hash = dict() + + # for loop nums to set count for each element in hash(dictionary) + for num in nums: + if num in hash: + hash[num] += 1 + else: + hash[num] = 1 + + # sort (TimSort), using lambda function to set a sorting key which is a count + return sorted(hash, key=lambda x: hash[x], reverse=True)[:k] + +if __name__ == "__main__": + solution = Solution() + + # test case + nums_list = [ + [1,1,1,2,2,3], # [1, 2] + [1] # [1] + ] + k_list = [2, 1] + + for i in range(2): + nums = nums_list[i] + k = k_list[i] + result = solution.topKFrequent(nums, k) + print(f"start{i}") + print(f"input : {nums}, {k}") + print(f"result : {result}") + From a048d58cb128250388e82e1be17c6c6439234df0 Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 14:53:27 +0900 Subject: [PATCH 320/396] Feat: contains-duplicate Solution --- contains-duplicate/oddong.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 contains-duplicate/oddong.py diff --git a/contains-duplicate/oddong.py b/contains-duplicate/oddong.py new file mode 100644 index 000000000..80d16b535 --- /dev/null +++ b/contains-duplicate/oddong.py @@ -0,0 +1,19 @@ +a = [1, 2, 3, 5, 4] + +a.sort() + +print(a) +print(set(a)) +print(type(set(a))) + +convert_list_to_set = list(set(a)) + +print() +print(a) +print(convert_list_to_set) +print() + +if a == convert_list_to_set: + print(True) +else: + print(False) \ No newline at end of file From 081da4e824815c9248773294e6d0e0fdec1aa535 Mon Sep 17 00:00:00 2001 From: jonghun Date: Sat, 14 Dec 2024 14:56:29 +0900 Subject: [PATCH 321/396] add CRLF --- top-k-frequent-elements/JonghunLee.py | 1 - valid-palindrome/JonghunLee.py | 3 --- 2 files changed, 4 deletions(-) diff --git a/top-k-frequent-elements/JonghunLee.py b/top-k-frequent-elements/JonghunLee.py index 4dc1f9705..d2b585fed 100644 --- a/top-k-frequent-elements/JonghunLee.py +++ b/top-k-frequent-elements/JonghunLee.py @@ -38,4 +38,3 @@ def topKFrequent(self, nums: List[int], k: int) -> List[int]: print(f"start{i}") print(f"input : {nums}, {k}") print(f"result : {result}") - diff --git a/valid-palindrome/JonghunLee.py b/valid-palindrome/JonghunLee.py index 5a3cd64a8..65d011b7b 100644 --- a/valid-palindrome/JonghunLee.py +++ b/valid-palindrome/JonghunLee.py @@ -46,6 +46,3 @@ def check_palindrome(self, i, end, joined_string) -> bool: print(f"start {index} test") print(f"input : {test}") print(f"Is valid palindrome ? {solution.isPalindrome(test)}\n") - - - From a085b494ac86db8253c0402b2c085ca77413e83f Mon Sep 17 00:00:00 2001 From: jonghun Date: Sat, 14 Dec 2024 15:09:22 +0900 Subject: [PATCH 322/396] add filename --- contains-duplicate/{JonghunLee.py => rivkode.py} | 0 top-k-frequent-elements/{JonghunLee.py => rivkode.py} | 0 valid-palindrome/{JonghunLee.py => rivkode.py} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{JonghunLee.py => rivkode.py} (100%) rename top-k-frequent-elements/{JonghunLee.py => rivkode.py} (100%) rename valid-palindrome/{JonghunLee.py => rivkode.py} (100%) diff --git a/contains-duplicate/JonghunLee.py b/contains-duplicate/rivkode.py similarity index 100% rename from contains-duplicate/JonghunLee.py rename to contains-duplicate/rivkode.py diff --git a/top-k-frequent-elements/JonghunLee.py b/top-k-frequent-elements/rivkode.py similarity index 100% rename from top-k-frequent-elements/JonghunLee.py rename to top-k-frequent-elements/rivkode.py diff --git a/valid-palindrome/JonghunLee.py b/valid-palindrome/rivkode.py similarity index 100% rename from valid-palindrome/JonghunLee.py rename to valid-palindrome/rivkode.py From 4d07d50c6a05cf248b903bea8d602b88ee1222c8 Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 15:16:00 +0900 Subject: [PATCH 323/396] Feat: valid-palindrome Solution --- valid-palindrome/oddong.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 valid-palindrome/oddong.py diff --git a/valid-palindrome/oddong.py b/valid-palindrome/oddong.py new file mode 100644 index 000000000..0c27faa7b --- /dev/null +++ b/valid-palindrome/oddong.py @@ -0,0 +1,10 @@ +import re + +class Solution: + def isPalindrome(self, s: str) -> bool: + filtered_phrase = re.sub("[^a-zA-Z0-9]", "", s).lower() + + if filtered_phrase == filtered_phrase[::-1]: + return True + else: + return False From 72b43d143536723d96d3d4e6d0187fc1dba6ba27 Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 15:22:55 +0900 Subject: [PATCH 324/396] Feat: top-k-frequent-elements Solution --- top-k-frequent-elements/oddong.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 top-k-frequent-elements/oddong.py diff --git a/top-k-frequent-elements/oddong.py b/top-k-frequent-elements/oddong.py new file mode 100644 index 000000000..27a4d252e --- /dev/null +++ b/top-k-frequent-elements/oddong.py @@ -0,0 +1,5 @@ +import collections + +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + return [num for num, cnt in collections.Counter(nums).most_common(k)] From a9af1981ee03323d1f7c8984a302a63d25c8fb4e Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Fri, 13 Dec 2024 22:40:52 -0800 Subject: [PATCH 325/396] Valid palindrome --- valid-palindrome/EstherKim97.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 valid-palindrome/EstherKim97.py diff --git a/valid-palindrome/EstherKim97.py b/valid-palindrome/EstherKim97.py new file mode 100644 index 000000000..4accf4e50 --- /dev/null +++ b/valid-palindrome/EstherKim97.py @@ -0,0 +1,11 @@ +class Solution(object): + def isPalindrome(self, s): + import re + # remove all non-alphanumeric characters + s = re.sub(r'\W+', '', s.lower()) + + # check if the string is equal forward and backward + for i in range(len(s)//2): + if s[i] != s[-(i+1)]: + return False + return True From 32ed2baa8e51b39625f99ea72a780c6edca6e9ee Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 14 Dec 2024 15:41:53 +0900 Subject: [PATCH 326/396] top k frequent --- top-k-frequent-elements/eunhwa99.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 top-k-frequent-elements/eunhwa99.java diff --git a/top-k-frequent-elements/eunhwa99.java b/top-k-frequent-elements/eunhwa99.java new file mode 100644 index 000000000..cdc28da3e --- /dev/null +++ b/top-k-frequent-elements/eunhwa99.java @@ -0,0 +1,17 @@ + +import java.util.HashMap; +import java.util.Map; +class Solution { + public static int[] topKFrequent(int[] nums, int k) { + Map myMap = new HashMap<>(); + for (int num : nums) { + myMap.put(num, myMap.getOrDefault(num, 0) + 1); + } + return myMap.entrySet() + .stream() + .sorted((v1, v2) -> Integer.compare(v2.getValue(),v1.getValue())) + .map(Map.Entry::getKey) + .mapToInt(Integer::intValue) + .toArray(); + } +} \ No newline at end of file From da9d2bf3bc2b73349c1279b0677c5ff04c0aac7c Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 14 Dec 2024 15:47:50 +0900 Subject: [PATCH 327/396] =?UTF-8?q?=EC=A4=84=EB=B0=94=EA=BF=88=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- top-k-frequent-elements/eunhwa99.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/top-k-frequent-elements/eunhwa99.java b/top-k-frequent-elements/eunhwa99.java index cdc28da3e..c51eb02f5 100644 --- a/top-k-frequent-elements/eunhwa99.java +++ b/top-k-frequent-elements/eunhwa99.java @@ -1,4 +1,3 @@ - import java.util.HashMap; import java.util.Map; class Solution { @@ -14,4 +13,4 @@ public static int[] topKFrequent(int[] nums, int k) { .mapToInt(Integer::intValue) .toArray(); } -} \ No newline at end of file +} From 89ac2fec29b044c742923c2f35c930da00c51c5f Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 16:09:19 +0900 Subject: [PATCH 328/396] Feat: longest-consecutive-sequence Solution --- longest-consecutive-sequence/oddong.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 longest-consecutive-sequence/oddong.py diff --git a/longest-consecutive-sequence/oddong.py b/longest-consecutive-sequence/oddong.py new file mode 100644 index 000000000..dfafc50d1 --- /dev/null +++ b/longest-consecutive-sequence/oddong.py @@ -0,0 +1,17 @@ +class Solution: + def longestConsecutive(self, nums: List[int]) -> int: + if not nums: + return 0 + + nums = sorted(set(nums)) + longest_streak = 1 + current_streak = 1 + + for i in range(1, len(nums)): + if nums[i] == nums[i - 1] + 1: + current_streak += 1 + else: + longest_streak = max(longest_streak, current_streak) + current_streak = 1 + + return max(longest_streak, current_streak) From e603d1638ae0c496defc307c19ce5157ce78f2ca Mon Sep 17 00:00:00 2001 From: herrinekim Date: Fri, 13 Dec 2024 00:58:00 +0900 Subject: [PATCH 329/396] add solution: contains-duplicate --- contains-duplicate/HerrineKim.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 contains-duplicate/HerrineKim.js diff --git a/contains-duplicate/HerrineKim.js b/contains-duplicate/HerrineKim.js new file mode 100644 index 000000000..40bf2aa3b --- /dev/null +++ b/contains-duplicate/HerrineKim.js @@ -0,0 +1,16 @@ +// 시간복잡도: O(n) + +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function (nums) { + const seen = new Set(); + for (let num of nums) { + if (seen.has(num)) { + return true; // 중복 발견 + } + seen.add(num); + } + return false; // 모든 요소가 고유 +}; \ No newline at end of file From fec6b728289d0bf861677931b3def9add5994a0f Mon Sep 17 00:00:00 2001 From: herrinekim Date: Fri, 13 Dec 2024 20:42:19 +0900 Subject: [PATCH 330/396] add solution: valid-palindrome --- valid-palindrome/HerrineKim.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 valid-palindrome/HerrineKim.js diff --git a/valid-palindrome/HerrineKim.js b/valid-palindrome/HerrineKim.js new file mode 100644 index 000000000..84ccb14fa --- /dev/null +++ b/valid-palindrome/HerrineKim.js @@ -0,0 +1,23 @@ +// 시간복잡도: O(n) + +/** + * @param {string} s + * @return {boolean} + */ +var isPalindrome = function (s) { + // 전처리 - 알파벳과 숫자만 남기고 소문자로 변환 + const cleanString = s.toLowerCase().replace(/[^a-z0-9]/g, ""); + + // 양 끝에서 포인터를 이동하며 확인 + let left = 0, right = cleanString.length - 1; + + while (left < right) { + if (cleanString[left] !== cleanString[right]) { + return false; // 대칭이 깨지면 false + } + left++; + right--; + } + + return true; // 대칭이 유지되면 true +}; \ No newline at end of file From c56b72710d23d5a65b3f051d2b5b69f7003a8129 Mon Sep 17 00:00:00 2001 From: herrinekim Date: Fri, 13 Dec 2024 20:46:22 +0900 Subject: [PATCH 331/396] add solution: top-k-frequent-elements --- top-k-frequent-elements/HerrineKim.js | 30 +++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 top-k-frequent-elements/HerrineKim.js diff --git a/top-k-frequent-elements/HerrineKim.js b/top-k-frequent-elements/HerrineKim.js new file mode 100644 index 000000000..c8031e592 --- /dev/null +++ b/top-k-frequent-elements/HerrineKim.js @@ -0,0 +1,30 @@ +// 시간복잡도: O(n) + +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ +var topKFrequent = function (nums, k) { + // 빈도 계산 + const frequencyMap = new Map(); + for (let num of nums) { + frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1); + } + + // 버킷 정렬 + const bucket = Array(nums.length + 1).fill(null).map(() => []); + for (let [num, freq] of frequencyMap) { + bucket[freq].push(num); + } + + // 빈도 높은 요소들 추출 + const result = []; + for (let i = bucket.length - 1; i >= 0 && result.length < k; i--) { + if (bucket[i].length > 0) { + result.push(...bucket[i]); + } + } + + return result.slice(0, k); // 상위 k개의 요소 반환 +}; \ No newline at end of file From 1053604362ea44e890216f7081eb718b788b3422 Mon Sep 17 00:00:00 2001 From: herrinekim Date: Fri, 13 Dec 2024 20:52:55 +0900 Subject: [PATCH 332/396] add solution: longest-consecutive-sequence --- longest-consecutive-sequence/HerrineKim.js | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 longest-consecutive-sequence/HerrineKim.js diff --git a/longest-consecutive-sequence/HerrineKim.js b/longest-consecutive-sequence/HerrineKim.js new file mode 100644 index 000000000..ed986283c --- /dev/null +++ b/longest-consecutive-sequence/HerrineKim.js @@ -0,0 +1,31 @@ +// 시간복잡도: O(n) + +/** + * @param {number[]} nums + * @return {number} + */ +var longestConsecutive = function (nums) { + // Set을 사용해 중복 제거 + const numSet = new Set(nums); + let longestStreak = 0; + + // 각 숫자를 기준으로 연속 시퀀스를 탐색 + for (let num of numSet) { + // num이 시퀀스의 시작점인 경우만 탐색 + if (!numSet.has(num - 1)) { + let currentNum = num; + let currentStreak = 1; + + // 현재 시퀀스를 따라가며 길이 계산 + while (numSet.has(currentNum + 1)) { + currentNum++; + currentStreak++; + } + + // 최대 길이를 업데이트 + longestStreak = Math.max(longestStreak, currentStreak); + } + } + + return longestStreak; +}; \ No newline at end of file From 0e61080dcc1d2a393ba803c12a77121d2780e9b5 Mon Sep 17 00:00:00 2001 From: herrinekim Date: Fri, 13 Dec 2024 21:02:38 +0900 Subject: [PATCH 333/396] add solution: house-robber --- house-robber/HerrineKim.js | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 house-robber/HerrineKim.js diff --git a/house-robber/HerrineKim.js b/house-robber/HerrineKim.js new file mode 100644 index 000000000..9d327ae24 --- /dev/null +++ b/house-robber/HerrineKim.js @@ -0,0 +1,24 @@ +// 시간복잡도: O(n) + +/** + * @param {number[]} nums + * @return {number} + */ +var rob = function (nums) { + const n = nums.length; + if (n === 0) return 0; + if (n === 1) return nums[0]; + + // DP 배열 초기화 + let prev2 = 0; // dp[i-2] + let prev1 = 0; // dp[i-1] + + // 최대 수익 계산 + for (let num of nums) { + const current = Math.max(prev1, prev2 + num); + prev2 = prev1; + prev1 = current; + } + + return prev1; +}; From 6659921a46f426783d05a8064dc311d465c8adef Mon Sep 17 00:00:00 2001 From: herrinekim Date: Fri, 13 Dec 2024 21:09:16 +0900 Subject: [PATCH 334/396] fix: lint --- contains-duplicate/HerrineKim.js | 2 +- longest-consecutive-sequence/HerrineKim.js | 2 +- top-k-frequent-elements/HerrineKim.js | 2 +- valid-palindrome/HerrineKim.js | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/contains-duplicate/HerrineKim.js b/contains-duplicate/HerrineKim.js index 40bf2aa3b..1ac0ab86b 100644 --- a/contains-duplicate/HerrineKim.js +++ b/contains-duplicate/HerrineKim.js @@ -13,4 +13,4 @@ var containsDuplicate = function (nums) { seen.add(num); } return false; // 모든 요소가 고유 -}; \ No newline at end of file +}; diff --git a/longest-consecutive-sequence/HerrineKim.js b/longest-consecutive-sequence/HerrineKim.js index ed986283c..c204a0403 100644 --- a/longest-consecutive-sequence/HerrineKim.js +++ b/longest-consecutive-sequence/HerrineKim.js @@ -28,4 +28,4 @@ var longestConsecutive = function (nums) { } return longestStreak; -}; \ No newline at end of file +}; diff --git a/top-k-frequent-elements/HerrineKim.js b/top-k-frequent-elements/HerrineKim.js index c8031e592..b537ec7a1 100644 --- a/top-k-frequent-elements/HerrineKim.js +++ b/top-k-frequent-elements/HerrineKim.js @@ -27,4 +27,4 @@ var topKFrequent = function (nums, k) { } return result.slice(0, k); // 상위 k개의 요소 반환 -}; \ No newline at end of file +}; diff --git a/valid-palindrome/HerrineKim.js b/valid-palindrome/HerrineKim.js index 84ccb14fa..8c5b536f1 100644 --- a/valid-palindrome/HerrineKim.js +++ b/valid-palindrome/HerrineKim.js @@ -20,4 +20,4 @@ var isPalindrome = function (s) { } return true; // 대칭이 유지되면 true -}; \ No newline at end of file +}; From 14a128c9f4eed8def64802bf2eeb4cd928b4646a Mon Sep 17 00:00:00 2001 From: herrinekim Date: Sat, 14 Dec 2024 16:09:13 +0900 Subject: [PATCH 335/396] fix: add new line at the end --- contains-duplicate/HerrineKim.js | 1 + house-robber/HerrineKim.js | 1 + longest-consecutive-sequence/HerrineKim.js | 1 + top-k-frequent-elements/HerrineKim.js | 1 + valid-palindrome/HerrineKim.js | 1 + 5 files changed, 5 insertions(+) diff --git a/contains-duplicate/HerrineKim.js b/contains-duplicate/HerrineKim.js index 1ac0ab86b..ee5b0750a 100644 --- a/contains-duplicate/HerrineKim.js +++ b/contains-duplicate/HerrineKim.js @@ -14,3 +14,4 @@ var containsDuplicate = function (nums) { } return false; // 모든 요소가 고유 }; + diff --git a/house-robber/HerrineKim.js b/house-robber/HerrineKim.js index 9d327ae24..36013c74b 100644 --- a/house-robber/HerrineKim.js +++ b/house-robber/HerrineKim.js @@ -22,3 +22,4 @@ var rob = function (nums) { return prev1; }; + diff --git a/longest-consecutive-sequence/HerrineKim.js b/longest-consecutive-sequence/HerrineKim.js index c204a0403..454bef7a7 100644 --- a/longest-consecutive-sequence/HerrineKim.js +++ b/longest-consecutive-sequence/HerrineKim.js @@ -29,3 +29,4 @@ var longestConsecutive = function (nums) { return longestStreak; }; + diff --git a/top-k-frequent-elements/HerrineKim.js b/top-k-frequent-elements/HerrineKim.js index b537ec7a1..aae514d14 100644 --- a/top-k-frequent-elements/HerrineKim.js +++ b/top-k-frequent-elements/HerrineKim.js @@ -28,3 +28,4 @@ var topKFrequent = function (nums, k) { return result.slice(0, k); // 상위 k개의 요소 반환 }; + diff --git a/valid-palindrome/HerrineKim.js b/valid-palindrome/HerrineKim.js index 8c5b536f1..49989790f 100644 --- a/valid-palindrome/HerrineKim.js +++ b/valid-palindrome/HerrineKim.js @@ -21,3 +21,4 @@ var isPalindrome = function (s) { return true; // 대칭이 유지되면 true }; + From 389d6b8fb85d66997fc30d95c07eeb38efc0958b Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Fri, 13 Dec 2024 23:17:14 -0800 Subject: [PATCH 336/396] top k frequent element --- top-k-frequent-elements/EstherKim97.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 top-k-frequent-elements/EstherKim97.py diff --git a/top-k-frequent-elements/EstherKim97.py b/top-k-frequent-elements/EstherKim97.py new file mode 100644 index 000000000..54821d78e --- /dev/null +++ b/top-k-frequent-elements/EstherKim97.py @@ -0,0 +1,17 @@ +class Solution(object): + def topKFrequent(self, nums, k): + unique_no = set(nums) + data = [] + + for i in unique_no: + count = 0 + for j in nums: + if i == j: + count += 1 + data.append((count, i)) + + data = sorted(data, reverse=True, key=lambda x:[1]) + + return [x[1] for x in data[:k]] + + #nums.count(i) From a41297ff8b8eb64cccf0e8d22e76c54314fb42f6 Mon Sep 17 00:00:00 2001 From: donghyeon95 Date: Sat, 14 Dec 2024 16:25:48 +0900 Subject: [PATCH 337/396] feat: House Robber #264 --- house-robber/donghyeon95.java | 40 +++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 house-robber/donghyeon95.java diff --git a/house-robber/donghyeon95.java b/house-robber/donghyeon95.java new file mode 100644 index 000000000..e7c9fa0d0 --- /dev/null +++ b/house-robber/donghyeon95.java @@ -0,0 +1,40 @@ +import java.util.Arrays; + +class Solution { + private int[] dp; + + public int rob(int[] nums) { + // 점화식 + // f(x) = f(나를 선택) + f(나를 안선택) + // 100개라서 가능은 할 거 같다. + + dp = new int[100]; + + // 0도 가능 하다 + Arrays.fill(dp, -1); + + + return recurse(nums, 0); + + } + + public int recurse(int[] nums, int index) { + // 종료 조건 + if (index >= nums.length) return 0; + + // 이미 한번 처리가 되었다면 + if (dp[index] != -1) return dp[index]; + + int result = 0; + + // 나를 선택하는 경우, + result = Math.max(recurse(nums, index+2)+nums[index], result); + + // 나를 선택하지 않는 경우, + result = Math.max(recurse(nums, index+1), result); + + dp[index] = result; + return result; + } +} + From d71593fd4dcf68b22d59e459b2fcb51aaddba653 Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 16:26:11 +0900 Subject: [PATCH 338/396] Feat: house-robber Solution --- house-robber/oddong.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 house-robber/oddong.py diff --git a/house-robber/oddong.py b/house-robber/oddong.py new file mode 100644 index 000000000..bda3c8b68 --- /dev/null +++ b/house-robber/oddong.py @@ -0,0 +1,15 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + if not nums: + return 0 + elif len(nums) == 1: + return nums[0] + + dp = [0] * len(nums) + dp[0] = nums[0] + dp[1] = max(nums[0], nums[1]) + + for idx in range(2, len(nums)): + dp[idx] = max(nums[idx-1], nums[idx] + nums[idx-2]) + + return dp[-1] From 8dd3f2ea0f59c7900465c99589fc91a987049978 Mon Sep 17 00:00:00 2001 From: HC-kang Date: Sat, 14 Dec 2024 16:26:22 +0900 Subject: [PATCH 339/396] =?UTF-8?q?chore:=20=ED=8C=8C=EC=9D=BC=EB=AA=85=20?= =?UTF-8?q?=EC=B2=B4=ED=81=AC=20=EB=B0=A9=EC=8B=9D=EC=97=90=EC=84=9C=20reb?= =?UTF-8?q?ase=EA=B0=80=20=ED=95=84=EC=9A=94=ED=95=98=EC=A7=80=20=EC=95=8A?= =?UTF-8?q?=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/integration.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/integration.yaml b/.github/workflows/integration.yaml index b74a5f646..f805a71fa 100644 --- a/.github/workflows/integration.yaml +++ b/.github/workflows/integration.yaml @@ -85,7 +85,9 @@ jobs: - name: Check filename rules if: ${{ steps.pr-labels.outputs.has_maintenance != 'true' }} run: | - files=$(git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }} | tr -d '"') + # PR의 첫 커밋을 확인 + merge_base=$(git merge-base ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }}) + files=$(git diff --name-only $merge_base ${{ github.event.pull_request.head.sha }} | tr -d '"') pr_author="${{ github.event.pull_request.user.login }}" success=true From 1bd28b2b384955abf00d609cfbaa81e899346790 Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 16:28:07 +0900 Subject: [PATCH 340/396] Feat: contains-duplicate Solution --- contains-duplicate/oddong.py | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) diff --git a/contains-duplicate/oddong.py b/contains-duplicate/oddong.py index 80d16b535..74fefc4f2 100644 --- a/contains-duplicate/oddong.py +++ b/contains-duplicate/oddong.py @@ -1,19 +1,3 @@ -a = [1, 2, 3, 5, 4] - -a.sort() - -print(a) -print(set(a)) -print(type(set(a))) - -convert_list_to_set = list(set(a)) - -print() -print(a) -print(convert_list_to_set) -print() - -if a == convert_list_to_set: - print(True) -else: - print(False) \ No newline at end of file +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + return len(nums) != len(set(nums)) \ No newline at end of file From ba88544141757f3c0ff8bfd238a6cf8ec464edd2 Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 16:36:52 +0900 Subject: [PATCH 341/396] =?UTF-8?q?Fix:=20contains-duplicate=20=EB=88=84?= =?UTF-8?q?=EB=9D=BD=20=EA=B0=9C=ED=96=89=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/oddong.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/oddong.py b/contains-duplicate/oddong.py index 74fefc4f2..0648d87c5 100644 --- a/contains-duplicate/oddong.py +++ b/contains-duplicate/oddong.py @@ -1,3 +1,3 @@ class Solution: def containsDuplicate(self, nums: List[int]) -> bool: - return len(nums) != len(set(nums)) \ No newline at end of file + return len(nums) != len(set(nums)) From 898fa6f0acc517ea1f6e45af21649162b0c26835 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 14 Dec 2024 16:38:00 +0900 Subject: [PATCH 342/396] Longest Consecutive Sequence --- longest-consecutive-sequence/eunhwa99.java | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 longest-consecutive-sequence/eunhwa99.java diff --git a/longest-consecutive-sequence/eunhwa99.java b/longest-consecutive-sequence/eunhwa99.java new file mode 100644 index 000000000..eaa5d0b09 --- /dev/null +++ b/longest-consecutive-sequence/eunhwa99.java @@ -0,0 +1,23 @@ +import java.util.HashSet; + +class Solution { + public int longestConsecutive(int[] nums) { + HashSet mySet = new HashSet(); + + for (int num : nums) { + mySet.add(num); + } + + int result = 0; + for (int num : mySet) { + int cnt = 1; + if (!mySet.contains(num - 1)) { + while (mySet.contains(++num)) { + ++cnt; + } + result = Math.max(cnt, result); + } + } + return result; + } +} From 0b5bd6c447709e3af49bc84b5d49231c259402ea Mon Sep 17 00:00:00 2001 From: o-ddong Date: Sat, 14 Dec 2024 16:40:23 +0900 Subject: [PATCH 343/396] =?UTF-8?q?Fix:=20=ED=8C=8C=EC=9D=BC=EB=AA=85=20?= =?UTF-8?q?=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/{oddong.py => o-ddong.py} | 0 house-robber/{oddong.py => o-ddong.py} | 0 longest-consecutive-sequence/{oddong.py => o-ddong.py} | 0 top-k-frequent-elements/{oddong.py => o-ddong.py} | 0 valid-palindrome/{oddong.py => o-ddong.py} | 0 5 files changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{oddong.py => o-ddong.py} (100%) rename house-robber/{oddong.py => o-ddong.py} (100%) rename longest-consecutive-sequence/{oddong.py => o-ddong.py} (100%) rename top-k-frequent-elements/{oddong.py => o-ddong.py} (100%) rename valid-palindrome/{oddong.py => o-ddong.py} (100%) diff --git a/contains-duplicate/oddong.py b/contains-duplicate/o-ddong.py similarity index 100% rename from contains-duplicate/oddong.py rename to contains-duplicate/o-ddong.py diff --git a/house-robber/oddong.py b/house-robber/o-ddong.py similarity index 100% rename from house-robber/oddong.py rename to house-robber/o-ddong.py diff --git a/longest-consecutive-sequence/oddong.py b/longest-consecutive-sequence/o-ddong.py similarity index 100% rename from longest-consecutive-sequence/oddong.py rename to longest-consecutive-sequence/o-ddong.py diff --git a/top-k-frequent-elements/oddong.py b/top-k-frequent-elements/o-ddong.py similarity index 100% rename from top-k-frequent-elements/oddong.py rename to top-k-frequent-elements/o-ddong.py diff --git a/valid-palindrome/oddong.py b/valid-palindrome/o-ddong.py similarity index 100% rename from valid-palindrome/oddong.py rename to valid-palindrome/o-ddong.py From 378a09601d1484f70e9708f2f8aaf60787e0af3f Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 14 Dec 2024 16:57:59 +0900 Subject: [PATCH 344/396] House Robber --- house-robber/eunhwa99.java | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 house-robber/eunhwa99.java diff --git a/house-robber/eunhwa99.java b/house-robber/eunhwa99.java new file mode 100644 index 000000000..0ed741be9 --- /dev/null +++ b/house-robber/eunhwa99.java @@ -0,0 +1,24 @@ +import java.util.Arrays; + +class Solution { + int size = 0; + int[] numArray; + int[] dp; + + public int rob(int[] nums) { + size = nums.length; + dp = new int[size]; + // 배열의 모든 값을 -1로 변경 + Arrays.fill(dp, -1); + numArray = nums; + return fun(0); + } + + private int fun(int idx) { + if (idx >= size) return 0; + if (dp[idx] != -1) return dp[idx]; + dp[idx] = 0; // check + dp[idx] += Math.max(fun(idx + 2) + numArray[idx], fun(idx + 1)); + return dp[idx]; + } +} \ No newline at end of file From be10c6cc4cd156aab2cf6ca6a753a134c099ad9f Mon Sep 17 00:00:00 2001 From: HC-kang Date: Sat, 14 Dec 2024 16:59:04 +0900 Subject: [PATCH 345/396] =?UTF-8?q?chore:=20=EC=9B=8C=ED=81=AC=ED=94=8C?= =?UTF-8?q?=EB=A1=9C=EC=9A=B0=20=EB=94=94=EB=B2=84=EA=B9=85=EC=9D=84=20?= =?UTF-8?q?=EC=9C=84=ED=95=9C=20=EB=A9=94=EC=8B=9C=EC=A7=80=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/integration.yaml | 50 +++++++++++++++++++++++++++--- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/.github/workflows/integration.yaml b/.github/workflows/integration.yaml index f805a71fa..c0ae2d81f 100644 --- a/.github/workflows/integration.yaml +++ b/.github/workflows/integration.yaml @@ -15,11 +15,19 @@ jobs: - name: Get PR labels id: pr-labels run: | + echo "🔍 PR 번호: ${{ github.event.pull_request.number }}" pr_number="${{ github.event.pull_request.number }}" + + echo "📋 PR 라벨 조회 중..." labels_json=$(gh pr view $pr_number --json labels -q '.labels[].name') + echo "확인된 라벨: $labels_json" + if [ -n "$labels_json" ]; then - echo "has_maintenance=$(echo $labels_json | grep -q 'maintenance' && echo 'true' || echo 'false')" >> $GITHUB_OUTPUT + has_maintenance=$(echo $labels_json | grep -q 'maintenance' && echo 'true' || echo 'false') + echo "maintenance 라벨 포함 여부: $has_maintenance" + echo "has_maintenance=$has_maintenance" >> $GITHUB_OUTPUT else + echo "maintenance 라벨이 없는 PR입니다. 파일명 규칙 검사를 진행합니다." echo "has_maintenance=false" >> $GITHUB_OUTPUT fi env: @@ -28,35 +36,46 @@ jobs: # 줄바꿈 체크 - name: Check for missing end line breaks run: | - # 따옴표를 제거하고 파일 목록 가져오기 + echo "🔍 줄바꿈 검사 시작" + echo "기준 커밋: ${{ github.event.pull_request.base.sha }}" + echo "현재 커밋: ${{ github.sha }}" + files=$(git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | tr -d '"') success=true - echo "변경된 파일 목록:" + echo "📝 변경된 파일 목록:" echo "$files" echo "## 줄바꿈 누락 파일" >> $GITHUB_STEP_SUMMARY for file in $files; do + echo "검사 중: $file" if [ -s "$file" ] && [ "$(tail -c 1 $file | wc -l)" -eq 0 ]; then - echo "발견된 줄바꿈 누락: $file" + echo "❌ 줄바꿈 누락: $file" echo "- $file" >> $GITHUB_STEP_SUMMARY success=false + else + echo "✅ 정상: $file" fi done if [ "$success" = false ]; then + echo "⚠️ 줄바꿈 검사 실패" echo -e "\n:warning: 파일 끝의 누락된 줄바꿈을 추가해 주세요." >> $GITHUB_STEP_SUMMARY exit 1 + else + echo "✅ 모든 파일의 줄바꿈 정상" fi # 제어문자 체크 - name: Check for control characters in filenames run: | + echo "🔍 파일명 제어문자 검사 시작" files=$(git diff --name-only ${{ github.event.pull_request.base.sha }} ${{ github.sha }} | tr -d '"') success=true echo "## 제어문자가 포함된 파일명" >> $GITHUB_STEP_SUMMARY for file in $files; do + echo "검사 중: $file" # basename으로 파일명만 추출하고 따옴표 제거 filename=$(basename "$file" | tr -d '"') @@ -71,45 +90,66 @@ jobs: # 이스케이프 시퀀스 체크 [[ "$filename" =~ (\\[0-7]{1,3}|\\x[0-9a-fA-F]{1,2}) ]]; then + echo "❌ 제어문자 발견: $file" echo "- $file (제어문자 포함)" >> $GITHUB_STEP_SUMMARY success=false + else + echo "✅ 정상: $file" fi done if [ "$success" = false ]; then + echo "⚠️ 제어문자 검사 실패" echo -e "\n:warning: 파일명에서 제어문자를 제거해 주세요." >> $GITHUB_STEP_SUMMARY exit 1 + else + echo "✅ 모든 파일명이 제어문자 없이 정상" fi # 파일명 규칙 체크 - maintenance 라벨이 없는 경우에만 실행 - name: Check filename rules if: ${{ steps.pr-labels.outputs.has_maintenance != 'true' }} run: | - # PR의 첫 커밋을 확인 + echo "🔍 파일명 규칙 검사 시작" + echo "PR 작성자: ${{ github.event.pull_request.user.login }}" + + # PR의 공통 조상 커밋을 찾아서 merge base로 설정 merge_base=$(git merge-base ${{ github.event.pull_request.base.sha }} ${{ github.event.pull_request.head.sha }}) + echo "Merge base 커밋: $merge_base" + files=$(git diff --name-only $merge_base ${{ github.event.pull_request.head.sha }} | tr -d '"') pr_author="${{ github.event.pull_request.user.login }}" success=true + echo "📝 검사할 파일 목록:" + echo "$files" + echo "## 파일명 규칙 위반" >> $GITHUB_STEP_SUMMARY for file in $files; do if [ -f "$file" ]; then + echo "검사 중: $file" # 파일명만 추출 (경로 제외) filename=$(basename "$file") # 파일명이 GitHub계정명인지 확인 shopt -s nocasematch if [[ ! "$filename" = "$pr_author"* ]]; then + echo "❌ 규칙 위반: $file" echo "- $file" >> $GITHUB_STEP_SUMMARY success=false + else + echo "✅ 정상: $file" fi fi done if [ "$success" = false ]; then + echo "⚠️ 파일명 규칙 검사 실패" echo -e "\n:warning: 파일명은 반드시 'GitHub계정명' 또는 'GitHub계정명-xxx' 형식으로 해주셔야 합니다. (예: ${pr_author}.ts, ${pr_author}-1.ts, ${pr_author}-2.ts)" >> $GITHUB_STEP_SUMMARY exit 1 + else + echo "✅ 모든 파일명이 규칙에 맞게 정상" fi env: GH_TOKEN: ${{ github.token }} From 4c8241e366c798a35d78463d396fc3c7e9d5ccb2 Mon Sep 17 00:00:00 2001 From: eunhwa99 Date: Sat, 14 Dec 2024 16:59:44 +0900 Subject: [PATCH 346/396] Add line --- house-robber/eunhwa99.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/house-robber/eunhwa99.java b/house-robber/eunhwa99.java index 0ed741be9..bcf0d5ffc 100644 --- a/house-robber/eunhwa99.java +++ b/house-robber/eunhwa99.java @@ -21,4 +21,4 @@ private int fun(int idx) { dp[idx] += Math.max(fun(idx + 2) + numArray[idx], fun(idx + 1)); return dp[idx]; } -} \ No newline at end of file +} From 78148bccc775777d480f5e204a75f899817224be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=9D=80=EB=B9=88=20Eunbeen=20Kang?= Date: Thu, 12 Dec 2024 13:11:05 +0900 Subject: [PATCH 347/396] Contains Duplicate Solution --- contains-duplicate/river20s.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 contains-duplicate/river20s.java diff --git a/contains-duplicate/river20s.java b/contains-duplicate/river20s.java new file mode 100644 index 000000000..44b621e5d --- /dev/null +++ b/contains-duplicate/river20s.java @@ -0,0 +1,15 @@ +import java.util.HashSet; + +class Solution { + public boolean containsDuplicate(int[] nums) { + HashSet set = new HashSet<>(); + + for (int num : nums) { + if (!set.add(num)) { + return true; + } + } + + return false; + } +} \ No newline at end of file From 244d4880bd301194b8b1047219065b2fa2d75951 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=9D=80=EB=B9=88=20Eunbeen=20Kang?= Date: Thu, 12 Dec 2024 13:18:17 +0900 Subject: [PATCH 348/396] Valid Palindrome Solution --- valid-palindrome/river20s.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 valid-palindrome/river20s.java diff --git a/valid-palindrome/river20s.java b/valid-palindrome/river20s.java new file mode 100644 index 000000000..29c87e334 --- /dev/null +++ b/valid-palindrome/river20s.java @@ -0,0 +1,15 @@ +class Solution { + public boolean isPalindrome(String s) { + + // 문자열 s의 대문자를 소문자로 치환한다. + String lowerCase = s.toLowerCase(); + // 소문자 a-z, 숫자 0-9에 해당하지 않는 문자를 지운다. + String alphanumeric = lowerCase.replaceAll("[^a-z0-9]", ""); + // 뒤집은 문자열을 만든다. + String reverse = new StringBuilder(alphanumeric).reverse().toString(); + // 두 문자열을 비교한다. + boolean isEqual = alphanumeric.equals(reverse); + + return isEqual; + } +} \ No newline at end of file From 3e8b379b5acba808dfa176cc4f69f6c7437c49fb Mon Sep 17 00:00:00 2001 From: river20s Date: Sat, 14 Dec 2024 22:17:13 +0900 Subject: [PATCH 349/396] =?UTF-8?q?=EB=A6=AC=EB=B2=A0=EC=9D=B4=EC=8A=A4?= =?UTF-8?q?=EB=A5=BC=20=EC=9C=84=ED=95=9C=20=EB=B3=80=EA=B2=BD=EC=82=AC?= =?UTF-8?q?=ED=95=AD=20=EC=BB=A4=EB=B0=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/river20s.java | 28 ++++++++++++++-------------- valid-palindrome/river20s.java | 28 ++++++++++++++-------------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/contains-duplicate/river20s.java b/contains-duplicate/river20s.java index 44b621e5d..c2f213fb4 100644 --- a/contains-duplicate/river20s.java +++ b/contains-duplicate/river20s.java @@ -1,15 +1,15 @@ -import java.util.HashSet; - -class Solution { - public boolean containsDuplicate(int[] nums) { - HashSet set = new HashSet<>(); - - for (int num : nums) { - if (!set.add(num)) { - return true; - } - } - - return false; - } +import java.util.HashSet; + +class Solution { + public boolean containsDuplicate(int[] nums) { + HashSet set = new HashSet<>(); + + for (int num : nums) { + if (!set.add(num)) { + return true; + } + } + + return false; + } } \ No newline at end of file diff --git a/valid-palindrome/river20s.java b/valid-palindrome/river20s.java index 29c87e334..c238bcfce 100644 --- a/valid-palindrome/river20s.java +++ b/valid-palindrome/river20s.java @@ -1,15 +1,15 @@ -class Solution { - public boolean isPalindrome(String s) { - - // 문자열 s의 대문자를 소문자로 치환한다. - String lowerCase = s.toLowerCase(); - // 소문자 a-z, 숫자 0-9에 해당하지 않는 문자를 지운다. - String alphanumeric = lowerCase.replaceAll("[^a-z0-9]", ""); - // 뒤집은 문자열을 만든다. - String reverse = new StringBuilder(alphanumeric).reverse().toString(); - // 두 문자열을 비교한다. - boolean isEqual = alphanumeric.equals(reverse); - - return isEqual; - } +class Solution { + public boolean isPalindrome(String s) { + + // 문자열 s의 대문자를 소문자로 치환한다. + String lowerCase = s.toLowerCase(); + // 소문자 a-z, 숫자 0-9에 해당하지 않는 문자를 지운다. + String alphanumeric = lowerCase.replaceAll("[^a-z0-9]", ""); + // 뒤집은 문자열을 만든다. + String reverse = new StringBuilder(alphanumeric).reverse().toString(); + // 두 문자열을 비교한다. + boolean isEqual = alphanumeric.equals(reverse); + + return isEqual; + } } \ No newline at end of file From fcb623288a6420973d2c5eaf707866c3ffab45cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=9D=80=EB=B9=88=20Eunbeen=20Kang?= Date: Sat, 14 Dec 2024 22:30:38 +0900 Subject: [PATCH 350/396] =?UTF-8?q?=EA=B0=9C=ED=96=89=EB=AC=B8=EC=9E=90=20?= =?UTF-8?q?=EB=88=84=EB=9D=BD=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/river20s.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contains-duplicate/river20s.java b/contains-duplicate/river20s.java index c2f213fb4..9ae0ab2c9 100644 --- a/contains-duplicate/river20s.java +++ b/contains-duplicate/river20s.java @@ -12,4 +12,5 @@ public boolean containsDuplicate(int[] nums) { return false; } -} \ No newline at end of file +} + From addf98532ae8eb62ef7dbc6055ee0e0d3aab8b92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=9D=80=EB=B9=88=20Eunbeen=20Kang?= Date: Sat, 14 Dec 2024 22:35:57 +0900 Subject: [PATCH 351/396] =?UTF-8?q?=EB=88=84=EB=9D=BD=EB=90=9C=20=EA=B0=9C?= =?UTF-8?q?=ED=96=89=EB=AC=B8=EC=9E=90=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- valid-palindrome/river20s.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/valid-palindrome/river20s.java b/valid-palindrome/river20s.java index c238bcfce..8df5f20d4 100644 --- a/valid-palindrome/river20s.java +++ b/valid-palindrome/river20s.java @@ -12,4 +12,5 @@ public boolean isPalindrome(String s) { return isEqual; } -} \ No newline at end of file +} + From 0a20726e9b3a6d9d089ec2129a127652b70e0322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B0=95=EC=9D=80=EB=B9=88=20Eunbeen=20Kang?= Date: Sat, 14 Dec 2024 22:41:03 +0900 Subject: [PATCH 352/396] =?UTF-8?q?indent=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/river20s.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/river20s.java b/contains-duplicate/river20s.java index 9ae0ab2c9..e94c0bfd5 100644 --- a/contains-duplicate/river20s.java +++ b/contains-duplicate/river20s.java @@ -10,7 +10,7 @@ public boolean containsDuplicate(int[] nums) { } } - return false; + return false; } } From 47b2de270be556ba7d7e666a751c4f47e224ae00 Mon Sep 17 00:00:00 2001 From: TotschKa Date: Sat, 14 Dec 2024 23:31:01 +0900 Subject: [PATCH 353/396] house robber --- house-robber/Totschka.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 house-robber/Totschka.ts diff --git a/house-robber/Totschka.ts b/house-robber/Totschka.ts new file mode 100644 index 000000000..91e92b254 --- /dev/null +++ b/house-robber/Totschka.ts @@ -0,0 +1,18 @@ +// https://leetcode.com/problems/house-robber/ +let dp; +function rob(nums: number[]): number { + dp = Array.from({ length: nums.length + 1 }, () => -1); + return doRobbery(nums, nums.length - 1); +} + +function doRobbery(nums: number[], i: number) { + if (i < 0) { + return 0; + } + if (dp[i] >= 0) { + return dp[i]; + } + const money = Math.max(doRobbery(nums, i - 2) + nums[i], doRobbery(nums, i - 1)); + dp[i] = money; + return money; +} From 671a3f66d123ce1b4a4d7c116ccd43a94cb72f19 Mon Sep 17 00:00:00 2001 From: YeomChaeeun Date: Sun, 15 Dec 2024 00:55:58 +0900 Subject: [PATCH 354/396] =?UTF-8?q?fix:=20=EB=A1=9C=EC=A7=81=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/YeomChaeeun.ts | 1 - longest-consecutive-sequence/YeomChaeeun.ts | 16 +++++----------- top-k-frequent-elements/YeomChaeeun.ts | 18 ++++-------------- valid-palindrome/YeomChaeeun.ts | 10 ++++------ 4 files changed, 13 insertions(+), 32 deletions(-) diff --git a/contains-duplicate/YeomChaeeun.ts b/contains-duplicate/YeomChaeeun.ts index 91a455119..4b451286a 100644 --- a/contains-duplicate/YeomChaeeun.ts +++ b/contains-duplicate/YeomChaeeun.ts @@ -26,7 +26,6 @@ function containsDuplicate(nums: number[]): boolean { let obj={} for(let i = 0; i < nums.length; i++) { - console.log('nums >>', nums[i], 'obj >>', obj) if(obj[nums[i]]) { return true; } diff --git a/longest-consecutive-sequence/YeomChaeeun.ts b/longest-consecutive-sequence/YeomChaeeun.ts index 4e3d0629c..3c5ea5b3f 100644 --- a/longest-consecutive-sequence/YeomChaeeun.ts +++ b/longest-consecutive-sequence/YeomChaeeun.ts @@ -28,23 +28,17 @@ function longestConsecutive(nums: number[]): number { // ========= let longest = 0; - let temp = 1; - + let current = 1; for(let i = 0; i < nums.length-1; i++) { - if(nums[i] === nums[i + 1]) { - // console.log(nums[i], '===', nums[i+1]) + if(nums[i] === nums[i - 1]) { continue; } else if(nums[i] + 1 === nums[i + 1] ) { - // console.log(nums[i], '+ 1 =', nums[i+1]) - temp += 1; + current += 1; } else { - // console.log(longest, ' - ', temp) - longest = Math.max(temp, longest); - temp = 1; + longest = Math.max(current, longest); + current = 1; } } - // i가 마지막인 경우 for문의 else문을 타지 않으므로 다시 한번 체크함 - longest = Math.max(temp, longest); return longest; }; diff --git a/top-k-frequent-elements/YeomChaeeun.ts b/top-k-frequent-elements/YeomChaeeun.ts index efaa6b6e5..062a531ed 100644 --- a/top-k-frequent-elements/YeomChaeeun.ts +++ b/top-k-frequent-elements/YeomChaeeun.ts @@ -12,18 +12,8 @@ function topKFrequent(nums: number[], k: number): number[] { ++obj[num] } - // 배열로 변경 - let entries = Object.entries(obj) - // 정렬 - let sort_arr = entries.sort((a, b) => Number(b[1]) - Number(a[1])); - - let result = []; - let l = 0; - for(const item of sort_arr) { - if(l == k) break; - result.push(Number(item[0])); - l++; - } - - return result; + return Object.entries(obj) + .sort((a, b) => Number(b[1]) - Number(a[1])) + .slice(0, k) + .map(entry => Number(entry[0])); }; diff --git a/valid-palindrome/YeomChaeeun.ts b/valid-palindrome/YeomChaeeun.ts index 1a2ddc5d9..fd42a542d 100644 --- a/valid-palindrome/YeomChaeeun.ts +++ b/valid-palindrome/YeomChaeeun.ts @@ -4,14 +4,12 @@ */ function isPalindrome(s: string): boolean { let word = s.toLowerCase(); - const reg = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\" ]/g; - + const reg = /[^a-z0-9]/g; // removing all non-alphanumeric characters word = word.replace(reg, ''); + for(let i = 0; i < word.length; i++) { - for(let j = word.length-i-1; j >= word.length-i-1; j--) { - // console.log(word[i], '===', word[j]) - if(word[i] !== word[j]) return false; - } + if(word[i] !== word[word.length-i-1]) + return false; } return true; }; From 9401d2536f93b88b23cc121933118652ef12dfee Mon Sep 17 00:00:00 2001 From: nakjun <111031253+nakjun12@users.noreply.github.com> Date: Sun, 15 Dec 2024 07:34:00 +0900 Subject: [PATCH 355/396] add valid-palindrome solution --- valid-palindrome/nakjun12.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 valid-palindrome/nakjun12.ts diff --git a/valid-palindrome/nakjun12.ts b/valid-palindrome/nakjun12.ts new file mode 100644 index 000000000..7c6460df8 --- /dev/null +++ b/valid-palindrome/nakjun12.ts @@ -0,0 +1,11 @@ +function isPalindrome(s: string): boolean { + const convertWord = s.toLowerCase().match(/[a-z0-9]/g) ?? []; + const length = convertWord.length; + for (let i = 0; i < length / 2; i++) { + if (convertWord[i] !== convertWord[length - 1 - i]) { + return false; + } + } + + return true; +} From 53ef44ed25f51d1fdabfae280cde1ccd8ebe25a3 Mon Sep 17 00:00:00 2001 From: nakjun <111031253+nakjun12@users.noreply.github.com> Date: Sun, 15 Dec 2024 07:34:26 +0900 Subject: [PATCH 356/396] add contains-duplicate solution --- contains-duplicate/nakjun12.js | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 contains-duplicate/nakjun12.js diff --git a/contains-duplicate/nakjun12.js b/contains-duplicate/nakjun12.js new file mode 100644 index 000000000..4305ee4d0 --- /dev/null +++ b/contains-duplicate/nakjun12.js @@ -0,0 +1,7 @@ +/** + * @param {number[]} nums + * @return {boolean} + */ +var containsDuplicate = function (nums) { + return new Set(nums).size !== nums.length; +}; From 2173819b2bd95ceede3c1b8e8c4b5164485fe5a3 Mon Sep 17 00:00:00 2001 From: Nayeon Date: Sun, 15 Dec 2024 08:01:02 +0900 Subject: [PATCH 357/396] Add placeholder file for 'Valid Anagram' problem --- valid-anagram/KwonNayeon.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 valid-anagram/KwonNayeon.py diff --git a/valid-anagram/KwonNayeon.py b/valid-anagram/KwonNayeon.py new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/valid-anagram/KwonNayeon.py @@ -0,0 +1 @@ + From 3322146bcacbfd18fb81a722143a1f6935a96e5f Mon Sep 17 00:00:00 2001 From: nakjun <111031253+nakjun12@users.noreply.github.com> Date: Sun, 15 Dec 2024 08:04:06 +0900 Subject: [PATCH 358/396] add top-k-frequent-elements solution --- top-k-frequent-elements/nakjun12.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 top-k-frequent-elements/nakjun12.ts diff --git a/top-k-frequent-elements/nakjun12.ts b/top-k-frequent-elements/nakjun12.ts new file mode 100644 index 000000000..f258b8899 --- /dev/null +++ b/top-k-frequent-elements/nakjun12.ts @@ -0,0 +1,11 @@ +function topKFrequent(nums: number[], k: number): number[] { + const frequency = nums.reduce( + (acc, n) => acc.set(n, (acc.get(n) ?? 0) + 1), + new Map() + ); + + return Array.from(frequency) + .sort((a, b) => b[1] - a[1]) + .slice(0, k) + .map((item) => item[0]); +} From bd7b3c2f9c864ef980fb4dc1bf61aaaca1aaa07c Mon Sep 17 00:00:00 2001 From: GangBean Date: Sun, 15 Dec 2024 11:13:22 +0900 Subject: [PATCH 359/396] feat: solve valid anagram --- valid-anagram/GangBean.java | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 valid-anagram/GangBean.java diff --git a/valid-anagram/GangBean.java b/valid-anagram/GangBean.java new file mode 100644 index 000000000..ae2690a71 --- /dev/null +++ b/valid-anagram/GangBean.java @@ -0,0 +1,31 @@ +class Solution { + public boolean isAnagram(String s, String t) { + /** + 1. 문제 이해. + - 아나그램: 문자의 순서만 바뀌었을 때 동일한 글자 + - 구성 문자와 숫자만 동일하면 아나그램 + 2. 풀이 방식 + - comapre s.length() with t.length() + - loop over s and t, count each word's character and it's count, and then save it as map(key-value pair structure) + - compare map of s and t + 3. Complexity + - time complexity: O(N) + - space complexity: O(N) + */ + + if (s.length() != s.length()) return false; + + Map sMap = new HashMap<>(); + Map tMap = new HashMap<>(); + + for (char c: s.toCharArray()) { + sMap.put(c, sMap.getOrDefault(c, 0) + 1); + } + for (char c: t.toCharArray()) { + tMap.put(c, tMap.getOrDefault(c, 0) + 1); + } + + return Objects.equals(sMap, tMap); + } +} + From 53dbe34f35a676db0e26b60de48a5a92e35def1f Mon Sep 17 00:00:00 2001 From: GangBean Date: Sun, 15 Dec 2024 12:27:41 +0900 Subject: [PATCH 360/396] feat: solve climbing stairs --- climbing-stairs/GangBean.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 climbing-stairs/GangBean.java diff --git a/climbing-stairs/GangBean.java b/climbing-stairs/GangBean.java new file mode 100644 index 000000000..a465565bd --- /dev/null +++ b/climbing-stairs/GangBean.java @@ -0,0 +1,35 @@ +class Solution { + public int climbStairs(int n) { + /** + 1. Understanding + - return the count of ways to climb up to top + - way means the sequence of step count + - each state, there can be 2 ways. first climb 1 step, second climb 2 step + 2. solve strategy + - assume the count of ways to climb up to K th stairs is C[K]. + - then, C[0] = 1, C[1] = 1, C[2] = 2(because, you can up to 2nd stair from 0th stair and also from 1st stair.) + - and C[3] = C[2] + C[1], C[4] = C[3] + C[2], ... etc... + - so we can fomulate C[k] = C[k-1] + C[k-2] + - iterate over 0 to n, you can caculate C[k]. + - and finally return C[n] is the answer. + + 3. complexity + - I answer to this part, along with coding upon each line description. + */ + + // 1. create array to demonstrate each stairs way count to reach that position. + // the maximun step count is 45, so maybe there is over 2^32(approximately 2 billion; so i worry about the overflow), I assign long type array. Oh.. but i catch that return type of this method is integer, so i can assume that maximum value is under integer range. So, assign as integer. + int[] c = new int[n + 1]; // the extra plus 1 means 0th stair state + // space complexity: O(n) + for (int stair = 0; stair <= n; stair++) { // time complexity O(n) + if (stair <= 1) { + c[stair] = 1; // O(1) + continue; + } + c[stair] = c[stair-1] + c[stair-2]; // O(1) + } + + return c[n]; + } +} + From 63f44837fa08c871ff733cc0ceeff9b3d11b99c6 Mon Sep 17 00:00:00 2001 From: hanseulhee <3021062@gmail.com> Date: Sun, 15 Dec 2024 13:03:47 +0900 Subject: [PATCH 361/396] top k frequent elements solution --- top-k-frequent-elements/hanseulhee.js | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 top-k-frequent-elements/hanseulhee.js diff --git a/top-k-frequent-elements/hanseulhee.js b/top-k-frequent-elements/hanseulhee.js new file mode 100644 index 000000000..6700114e4 --- /dev/null +++ b/top-k-frequent-elements/hanseulhee.js @@ -0,0 +1,22 @@ +/** + * @param {number[]} nums + * @param {number} k + * @return {number[]} + */ + +function topKFrequent(nums, k) { + // 숫자의 빈도를 저장할 Map 생성 + const frequency = new Map(); + + // 빈도 계산 + for (const num of nums) { + // Map에 이미 숫자가 있으면 +1, 없으면 1로 reset + frequency.set(num, (frequency.get(num) || 0) + 1); + } + + // 빈도 순으로 숫자 정렬 후 가장 빈도가 높은 k개의 숫자를 반환 + return [...frequency.entries()] // entries를 이용해 Map을 배열로 변환 + .sort((a, b) => b[1] - a[1]) + .slice(0, k) + .map(entry => entry[0]); +} From bd650381cf8fb0c180fdf7605d3717a1e462f262 Mon Sep 17 00:00:00 2001 From: hanseulhee <3021062@gmail.com> Date: Sun, 15 Dec 2024 13:11:49 +0900 Subject: [PATCH 362/396] longest consecutive sequence solution --- longest-consecutive-sequence/hanseulhee.js | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 longest-consecutive-sequence/hanseulhee.js diff --git a/longest-consecutive-sequence/hanseulhee.js b/longest-consecutive-sequence/hanseulhee.js new file mode 100644 index 000000000..d6e9eb0e9 --- /dev/null +++ b/longest-consecutive-sequence/hanseulhee.js @@ -0,0 +1,30 @@ +/** + * @param {number[]} nums + * @return {number} + */ + +var longestConsecutive = function (nums) { + // Set으로 배열에서 중복된 요소 제거 + const numSet = new Set(nums) + + // 최장 길이 + let longest = 0 + + // 배열을 돌며 첫 시작이 되는 숫자를 찾음 + for (const num of numSet) { + // 연속된 숫자의 시작은 num - 1이 Set에 존재하지 않는 숫자여야 함 + if (!numSet.has(num - 1)) { + let currentNum = num + let currentStreak = 1 + + while (numSet.has(currentNum + 1)) { + currentNum += 1 // 다음 숫자로 이동 + currentStreak += 1 // 연속된 길이 증가 + } + + longest = Math.max(longest, currentStreak) + } + } + + return longest +} From dff59b11d0cf33a3fbb4103894438ff674d1dc34 Mon Sep 17 00:00:00 2001 From: hanseulhee <3021062@gmail.com> Date: Sun, 15 Dec 2024 13:15:32 +0900 Subject: [PATCH 363/396] house robber solution --- house-robber/hanseulhee.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 house-robber/hanseulhee.js diff --git a/house-robber/hanseulhee.js b/house-robber/hanseulhee.js new file mode 100644 index 000000000..7ff0a74e4 --- /dev/null +++ b/house-robber/hanseulhee.js @@ -0,0 +1,20 @@ +/** + * @param {number[]} nums + * @return {number} + */ + +var rob = function (nums) { + // 집이 하나인 경우 + if (nums.length === 1) return nums[0] + + let prevMax = 0 // 두 집 전까지의 최대 금액 + let currMax = 0 // 이전 집까지의 최대 금액 + + for (let num of nums) { + let temp = currMax // 현재 최대 금액 + currMax = Math.max(currMax, prevMax + num) // 현재 집을 털거나 털지 않을 경우 중 큰 값 + prevMax = temp // 이전 집으로 이동 + } + + return currMax // 최대 금액 반환 +} From 67d0f735c271a08d63a6baff8556e77698a34639 Mon Sep 17 00:00:00 2001 From: Heejin Ham Date: Sun, 15 Dec 2024 15:37:40 +0900 Subject: [PATCH 364/396] =?UTF-8?q?[Week1]=20House=20Robber=20=EC=88=98?= =?UTF-8?q?=EC=A0=95.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- house-robber/gmlwls96.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/house-robber/gmlwls96.kt b/house-robber/gmlwls96.kt index 154d97fce..c1125dfd4 100644 --- a/house-robber/gmlwls96.kt +++ b/house-robber/gmlwls96.kt @@ -11,6 +11,6 @@ class Solution { if (index >= nums.size) { return 0 } - return nums[index] + rob_recursion(nums, index + 2) + return nums[index] + Integer.max(rob_recursion(nums, index + 2), rob_recursion(nums, index + 3)) } } From 45a049d2566ad7411bc2c246aa36488cbd5d1243 Mon Sep 17 00:00:00 2001 From: jeehay Date: Sun, 15 Dec 2024 17:29:26 +0900 Subject: [PATCH 365/396] Add valid-anagram solution --- valid-anagram/Jeehay28.js | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 valid-anagram/Jeehay28.js diff --git a/valid-anagram/Jeehay28.js b/valid-anagram/Jeehay28.js new file mode 100644 index 000000000..1ad1776b7 --- /dev/null +++ b/valid-anagram/Jeehay28.js @@ -0,0 +1,55 @@ +/** + * @param {string} s + * @param {string} t + * @return {boolean} + */ + +// 시간 복잡도: O(n) +// 공간 복잡도: O(n) + +var isAnagram = function (s, t) { + + if (s.length !== t.length) { + return false; + } + + let obj = {}; + + for (let k of s) { + obj[k] = (obj[k] || 0) + 1; + + } + + for (let k of t) { + if (obj[k] === undefined || obj[k] === 0) { + return false; + } + obj[k]--; + } + + return true; + +}; + +// 시간 복잡도: O(n log n) +// 공간 복잡도: O(n) + +// var isAnagram = function (s, t) { + +// if (s.length !== t.length) { +// return false; +// } + +// let sArr = s.split("").sort(); +// let tArr = t.split("").sort(); + +// for (let i = 0; i < sArr.length; i++) { +// if (sArr[i] !== tArr[i]) { +// return false; +// } +// } + +// return true; + +// }; + From 92dd60591c5576944269ef0a6a33c3bfc8498d33 Mon Sep 17 00:00:00 2001 From: jeehay Date: Sun, 15 Dec 2024 17:33:22 +0900 Subject: [PATCH 366/396] Revert "Add valid-anagram solution" This reverts commit 45a049d2566ad7411bc2c246aa36488cbd5d1243. --- valid-anagram/Jeehay28.js | 55 --------------------------------------- 1 file changed, 55 deletions(-) delete mode 100644 valid-anagram/Jeehay28.js diff --git a/valid-anagram/Jeehay28.js b/valid-anagram/Jeehay28.js deleted file mode 100644 index 1ad1776b7..000000000 --- a/valid-anagram/Jeehay28.js +++ /dev/null @@ -1,55 +0,0 @@ -/** - * @param {string} s - * @param {string} t - * @return {boolean} - */ - -// 시간 복잡도: O(n) -// 공간 복잡도: O(n) - -var isAnagram = function (s, t) { - - if (s.length !== t.length) { - return false; - } - - let obj = {}; - - for (let k of s) { - obj[k] = (obj[k] || 0) + 1; - - } - - for (let k of t) { - if (obj[k] === undefined || obj[k] === 0) { - return false; - } - obj[k]--; - } - - return true; - -}; - -// 시간 복잡도: O(n log n) -// 공간 복잡도: O(n) - -// var isAnagram = function (s, t) { - -// if (s.length !== t.length) { -// return false; -// } - -// let sArr = s.split("").sort(); -// let tArr = t.split("").sort(); - -// for (let i = 0; i < sArr.length; i++) { -// if (sArr[i] !== tArr[i]) { -// return false; -// } -// } - -// return true; - -// }; - From f5ef578c9e8fd07393a625b50449593800f9ef67 Mon Sep 17 00:00:00 2001 From: jeehay Date: Sun, 15 Dec 2024 17:38:24 +0900 Subject: [PATCH 367/396] Add house-robber solution --- house-robber/Jeehay28.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 house-robber/Jeehay28.js diff --git a/house-robber/Jeehay28.js b/house-robber/Jeehay28.js new file mode 100644 index 000000000..6fc9d239c --- /dev/null +++ b/house-robber/Jeehay28.js @@ -0,0 +1,36 @@ +/** + * @param {number[]} nums + * @return {number} + */ + +// Bottom-Up DP (with constant space) 방식 + +// 시간 복잡도 (Time Complexity) +// O(n) — 입력 배열의 크기에 비례하여 수행 시간이 증가 + +// 공간 복잡도 (Space Complexity) +// O(1) — 입력 크기에 관계없이 사용하는 메모리 공간이 일정 + + +var rob = function (nums) { + + if (nums.length === 1) { + return nums[0]; + } + + let robbed_2 = nums[0]; + let robbed_1 = Math.max(nums[0], nums[1]); + + for (let i = 2; i < nums.length; i++) { + + const temp = robbed_1; + + robbed_1 = Math.max(robbed_1, robbed_2 + nums[i]); + + robbed_2 = temp; + + } + + return robbed_1; + +}; From 4f4795bac9f25ae71612ab70b0a3a80869a6ea01 Mon Sep 17 00:00:00 2001 From: Taehun Lim Date: Sun, 8 Dec 2024 16:10:07 +0900 Subject: [PATCH 368/396] [First week][contains-duplicate] adds answer --- contains-duplicate/routiful.py | 37 ++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 contains-duplicate/routiful.py diff --git a/contains-duplicate/routiful.py b/contains-duplicate/routiful.py new file mode 100644 index 000000000..b708501c9 --- /dev/null +++ b/contains-duplicate/routiful.py @@ -0,0 +1,37 @@ +# FIRST WEEK + +# Question : 217. Contains Duplicate +# Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. + +# Example 1: +# Input: nums = [1,2,3,1] +# Output: true +# Explanation: +# The element 1 occurs at the indices 0 and 3. + +# Example 2: +# Input: nums = [1,2,3,4] +# Output: false +# Explanation: +# All elements are distinct. + +# Example 3: +# Input: nums = [1,1,1,3,3,4,3,2,4,2] +# Output: true + +# Constraints: +# 1 <= nums.length <= 105 +# -109 <= nums[i] <= 109 + +# Notes: +# Counts every elements(in the list) using 'count()' API. Luckily it is less than O(n) but maximum O(n) +# Makes Dict; the key is elements of the list. If the length of them are different, the list has duplicate elements. It is O(n) + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + d = {} + for n in nums: + d[n] = 1 + if len(d) != len(nums): + return True + return False From 5d3df3d006e0a30fddf2eb9b7c2de433cff37063 Mon Sep 17 00:00:00 2001 From: Taehun Lim Date: Sun, 15 Dec 2024 20:24:15 +0900 Subject: [PATCH 369/396] [First week][valid-palindrome] adds answer --- valid-palindrome/routiful.py | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 valid-palindrome/routiful.py diff --git a/valid-palindrome/routiful.py b/valid-palindrome/routiful.py new file mode 100644 index 000000000..bff3b1a86 --- /dev/null +++ b/valid-palindrome/routiful.py @@ -0,0 +1,59 @@ +# FIRST WEEK + +# Question : 125. Valid Palindrome + +# A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and +# removing all non-alphanumeric characters, it reads the same forward and backward. +# Alphanumeric characters include letters and numbers. +# Given a string s, return true if it is a palindrome, or false otherwise. + +# Example 1: +# Input: s = "A man, a plan, a canal: Panama" +# Output: true +# Explanation: "amanaplanacanalpanama" is a palindrome. + +# Example 2: +# Input: s = "race a car" +# Output: false +# Explanation: "raceacar" is not a palindrome. + +# Example 3: +# Input: s = " " +# Output: true +# Explanation: s is an empty string "" after removing non-alphanumeric characters. +# Since an empty string reads the same forward and backward, it is a palindrome. + +# Constraints: +# 1 <= s.length <= 2 * 105 +# s consists only of printable ASCII characters. + +# Notes: +# Using `reverse`(O(N)) api and matching all(max O(N)) look straightforward. +# The two pointer method may useful to decrease time complexity. +# If length of input is 0 or 1, return true. + +class Solution: + def isPalindrome(self, s: str) -> bool: + l = len(s) + if l < 2: + return True + + f = 0 + b = l - 1 + + while (f <= b): + if (s[f] == " " or (s[f].isalpha() == False and s[f].isnumeric() == False)): + f = f + 1 + continue + + if (s[b] == " " or (s[b].isalpha() == False and s[b].isnumeric() == False)): + b = b - 1 + continue + + if s[f].lower() != s[b].lower(): + return False + + f = f + 1 + b = b - 1 + + return True From 88e89757a29498455423202a1f52a3a5066a5b58 Mon Sep 17 00:00:00 2001 From: nakjun <111031253+nakjun12@users.noreply.github.com> Date: Sun, 15 Dec 2024 20:45:13 +0900 Subject: [PATCH 370/396] add longest-consecutive-sequence solution --- longest-consecutive-sequence/nakjun12.ts | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 longest-consecutive-sequence/nakjun12.ts diff --git a/longest-consecutive-sequence/nakjun12.ts b/longest-consecutive-sequence/nakjun12.ts new file mode 100644 index 000000000..a5a106a17 --- /dev/null +++ b/longest-consecutive-sequence/nakjun12.ts @@ -0,0 +1,25 @@ +/* + * TC: O(n) + * SC: O(n) + * */ +function longestConsecutive(nums: number[]): number { + if (nums.length === 0) return 0; + + const numSet = new Set(nums); + let longest = 0; + + for (const num of nums) { + if (numSet.has(num - 1)) { + continue; + } + + let length = 1; + while (numSet.has(num + length)) { + length++; + } + + longest = Math.max(length, longest); + } + + return longest; +} From cfe82dc93032abc470f3775fb669b1406f26902b Mon Sep 17 00:00:00 2001 From: easyone Date: Mon, 16 Dec 2024 07:27:09 +0900 Subject: [PATCH 371/396] Feat: Add solution of valid-anagram --- valid-anagram/easyone-jwlee.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 valid-anagram/easyone-jwlee.go diff --git a/valid-anagram/easyone-jwlee.go b/valid-anagram/easyone-jwlee.go new file mode 100644 index 000000000..136ac560c --- /dev/null +++ b/valid-anagram/easyone-jwlee.go @@ -0,0 +1,27 @@ +// 풀이 +// s의 rune을 key로 같은 철자의 갯수를 담게하고 +// t와 비교하면서 갯수를 하나씩 감소하게 해서 +// 남은 철자가 있거나 (s에는 있고, r에는 없는 철자가 있는 경우) +// 더 감소된 철자가 있으면 (s에는 없고, r에만 있는 철자가 있는 경우) false가 return 되게 함. + +// TC +// O(n+n+n) = O(n) + +// SC +// s의 길이만큼 늘어나는 map으로 인해 O(n) + +func isAnagram(s string, t string) bool { + m := make(map[rune]int) + for _, r := range s { + m[r]++ + } + for _, r := range t { + m[r]-- + } + for _, count := range m { + if count < 0 || count > 0 { + return false + } + } + return true +} From d95b42dcb78b3988876140c3a47c61f2cff8b4e2 Mon Sep 17 00:00:00 2001 From: easyone Date: Mon, 16 Dec 2024 07:58:42 +0900 Subject: [PATCH 372/396] Feat: Add solution of climbing-stairs --- climbing-stairs/easyone-jwlee.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 climbing-stairs/easyone-jwlee.go diff --git a/climbing-stairs/easyone-jwlee.go b/climbing-stairs/easyone-jwlee.go new file mode 100644 index 000000000..28e885655 --- /dev/null +++ b/climbing-stairs/easyone-jwlee.go @@ -0,0 +1,23 @@ +// 풀이 +// 1 일 때, 가능한 step은 1 -> 1가지 +// 2 일 때, 가능한 step은 1 1, 2 -> 2가지 +// 3 일 때, 가능한 step은 1 1 1, 1 2, 2 1 -> 3가지 +// n 일 때, 가능한 stop은 n-1의 가짓수에 1이 붙고, n-2의 가짓수에 2가 붙는다. + +// TC +// O(n) + +// SC +// int타입 변수만 사용해서 O(1) + +func climbStairs(n int) int { + if n <= 2 { + return n + } + prev := 1 // climb1 + curr := 2 // climb2 + for i := 3; i <= n; i++ { + prev, curr = curr, (curr + prev) + } + return curr +} From f83acab8d854b768a70c44045f79b96bf77d88d4 Mon Sep 17 00:00:00 2001 From: easyone Date: Mon, 16 Dec 2024 16:14:56 +0900 Subject: [PATCH 373/396] Feat: Add solution of 3sum --- 3sum/easyone-jwlee.go | 46 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 3sum/easyone-jwlee.go diff --git a/3sum/easyone-jwlee.go b/3sum/easyone-jwlee.go new file mode 100644 index 000000000..5ae6116c3 --- /dev/null +++ b/3sum/easyone-jwlee.go @@ -0,0 +1,46 @@ +// 풀이 +// 배열을 정렬하고 +// two pointer 사용 + +// TC +// 정렬 O(nlogn) + Two pointer 이중 루프 O(n^2) = O(n^2) + +// SC +// Go의 sort.Ints()는 TimSort를 사용. +// Merge Sort와 Insertion Sort의 조합으로 동작. +// 정렬 O(n) + Two pointer O(1) + 결과 배열 O(n) = O(n) + +func threeSum(nums []int) [][]int { + result := [][]int{} + sort.Ints(nums) // nums를 정렬 + + for i := 0; i < len(nums)-2; i++ { + if i > 0 && nums[i] == nums[i-1] { + continue // 중복된 값 건너뜀 + } + + left, right := i+1, len(nums)-1 + for left < right { + sum := nums[i] + nums[left] + nums[right] + if sum == 0 { + result = append(result, []int{nums[i], nums[left], nums[right]}) + left++ + right-- + + // 중복 제거 + for left < right && nums[left] == nums[left-1] { + left++ + } + for left < right && nums[right] == nums[right+1] { + right-- + } + } else if sum < 0 { + left++ + } else { + right-- + } + } + } + + return result +} From 190a83a2a7c93e006b015058d8eb601687e24925 Mon Sep 17 00:00:00 2001 From: Youngjae Kim Date: Mon, 16 Dec 2024 21:10:47 +0900 Subject: [PATCH 374/396] =?UTF-8?q?fix:=20=ED=8C=8C=EC=9D=BC=EB=AA=85=20?= =?UTF-8?q?=EA=B7=9C=EC=B9=99=20=EC=9C=84=EB=B0=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- contains-duplicate/YJason-K.ts | 1 + house-robber/YJason-K.ts | 1 + longest-consecutive-sequence/YJason-K.ts | 1 + top-k-frequent-elements/YJason-K.ts | 2 ++ valid-palindrome/YJason-K.ts | 1 + 5 files changed, 6 insertions(+) diff --git a/contains-duplicate/YJason-K.ts b/contains-duplicate/YJason-K.ts index 07cdb4f3a..ada16664e 100644 --- a/contains-duplicate/YJason-K.ts +++ b/contains-duplicate/YJason-K.ts @@ -15,3 +15,4 @@ function containsDuplicate(nums: number[]): boolean { } return false; }; + diff --git a/house-robber/YJason-K.ts b/house-robber/YJason-K.ts index 6a32fdb12..a62d74e95 100644 --- a/house-robber/YJason-K.ts +++ b/house-robber/YJason-K.ts @@ -28,3 +28,4 @@ function rob(nums: number[]): number { return prev1; // 마지막 집까지의 최대 금액 반환 } + diff --git a/longest-consecutive-sequence/YJason-K.ts b/longest-consecutive-sequence/YJason-K.ts index ceba08cd3..ae0f29a31 100644 --- a/longest-consecutive-sequence/YJason-K.ts +++ b/longest-consecutive-sequence/YJason-K.ts @@ -38,3 +38,4 @@ function longestConsecutive(nums: number[]): number { return longestSeq; // 가장 긴 연속 시퀀스의 길이 반환 } + diff --git a/top-k-frequent-elements/YJason-K.ts b/top-k-frequent-elements/YJason-K.ts index b406499e2..9f986bdc9 100644 --- a/top-k-frequent-elements/YJason-K.ts +++ b/top-k-frequent-elements/YJason-K.ts @@ -32,3 +32,5 @@ function topKFrequent(nums: number[], k: number): number[] { return sortedFrequent; } + + diff --git a/valid-palindrome/YJason-K.ts b/valid-palindrome/YJason-K.ts index b03871a5d..7ed4839fe 100644 --- a/valid-palindrome/YJason-K.ts +++ b/valid-palindrome/YJason-K.ts @@ -30,3 +30,4 @@ function isPalindrome(s: string): boolean { return true; } + From 84157c814c3b31159a805b162759824f0cb1612c Mon Sep 17 00:00:00 2001 From: Youngjae Kim <81736873+Yjason-K@users.noreply.github.com> Date: Mon, 16 Dec 2024 21:12:42 +0900 Subject: [PATCH 375/396] Rename YJason-K.ts to Yjason-K.ts --- contains-duplicate/{YJason-K.ts => Yjason-K.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{YJason-K.ts => Yjason-K.ts} (100%) diff --git a/contains-duplicate/YJason-K.ts b/contains-duplicate/Yjason-K.ts similarity index 100% rename from contains-duplicate/YJason-K.ts rename to contains-duplicate/Yjason-K.ts From 3454c2d217805e6631de339074d4ce174e2b6556 Mon Sep 17 00:00:00 2001 From: Youngjae Kim <81736873+Yjason-K@users.noreply.github.com> Date: Mon, 16 Dec 2024 21:13:17 +0900 Subject: [PATCH 376/396] Rename YJason-K.ts to Yjason-K.ts --- house-robber/{YJason-K.ts => Yjason-K.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename house-robber/{YJason-K.ts => Yjason-K.ts} (100%) diff --git a/house-robber/YJason-K.ts b/house-robber/Yjason-K.ts similarity index 100% rename from house-robber/YJason-K.ts rename to house-robber/Yjason-K.ts From e18b7695bd8fb1d3bd4b556e46e999e620b38cc2 Mon Sep 17 00:00:00 2001 From: Youngjae Kim <81736873+Yjason-K@users.noreply.github.com> Date: Mon, 16 Dec 2024 21:13:38 +0900 Subject: [PATCH 377/396] Rename YJason-K.ts to Yjason-K.ts --- longest-consecutive-sequence/{YJason-K.ts => Yjason-K.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename longest-consecutive-sequence/{YJason-K.ts => Yjason-K.ts} (100%) diff --git a/longest-consecutive-sequence/YJason-K.ts b/longest-consecutive-sequence/Yjason-K.ts similarity index 100% rename from longest-consecutive-sequence/YJason-K.ts rename to longest-consecutive-sequence/Yjason-K.ts From 2b8a3ba06f2b2d0aab912b954c12e9cc13d6d2fc Mon Sep 17 00:00:00 2001 From: Youngjae Kim <81736873+Yjason-K@users.noreply.github.com> Date: Mon, 16 Dec 2024 21:14:17 +0900 Subject: [PATCH 378/396] Rename YJason-K.ts to Yjason-K.ts --- top-k-frequent-elements/{YJason-K.ts => Yjason-K.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename top-k-frequent-elements/{YJason-K.ts => Yjason-K.ts} (100%) diff --git a/top-k-frequent-elements/YJason-K.ts b/top-k-frequent-elements/Yjason-K.ts similarity index 100% rename from top-k-frequent-elements/YJason-K.ts rename to top-k-frequent-elements/Yjason-K.ts From 07c39822aecda4737592eabc74969c5bd01a09e4 Mon Sep 17 00:00:00 2001 From: Youngjae Kim <81736873+Yjason-K@users.noreply.github.com> Date: Mon, 16 Dec 2024 21:14:55 +0900 Subject: [PATCH 379/396] Rename YJason-K.ts to Yjason-K.ts --- valid-palindrome/{YJason-K.ts => Yjason-K.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename valid-palindrome/{YJason-K.ts => Yjason-K.ts} (100%) diff --git a/valid-palindrome/YJason-K.ts b/valid-palindrome/Yjason-K.ts similarity index 100% rename from valid-palindrome/YJason-K.ts rename to valid-palindrome/Yjason-K.ts From 9264bff249bacad7710b67c0e2489abc27c32421 Mon Sep 17 00:00:00 2001 From: easyone Date: Tue, 17 Dec 2024 10:07:50 +0900 Subject: [PATCH 380/396] Feat: Add solution of construct-binary-tree-from-preorder-and-inorder-traversal --- .../easyone-jwlee.go | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go b/construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go new file mode 100644 index 000000000..5269e214e --- /dev/null +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go @@ -0,0 +1,50 @@ +// 풀이 +// preorder[0]이 제일 꼭대기 +// preorder 배열의 root index, inorder 배열의 시작, inorder 배열의 끝 +// 위의 세가지를 parameter로 받는 재귀함수를 만들어서 +// 왼쪽 서브트리, 오른쪽 서브트리를 순회 + +// TC +// map 만들기 O(n) + 재귀함수는 각 노드를 딱 한번씩만 방문하므로 O(n) = O(n) + +// SC +// map O(n) + 재귀함수 최악의 경우 한쪽으로만 노드가 이어지는 경우 O(n) = O(n) + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +func buildTree(preorder []int, inorder []int) *TreeNode { + inorderMap := make(map[int]int) + for i, n := range inorder { + inorderMap[n] = i + } + + var recursive func(rootIndex, inStart, inEnd int) *TreeNode + recursive = func(rootIndex, inStart, inEnd int) *TreeNode { + if rootIndex >= len(preorder) || inStart > inEnd { + return nil + } + rootVal := preorder[rootIndex] + rootInorderIndex := inorderMap[rootVal] + + result := &TreeNode{ + Val: rootVal, + } + + leftSize := rootInorderIndex - inStart + + result.Left = recursive(rootIndex+1, inStart, rootInorderIndex-1) + result.Right = recursive(rootIndex+1+leftSize, rootInorderIndex+1, inEnd) + + return result + } + + return recursive(0, 0, len(inorder)-1) +} + \ No newline at end of file From bc3a0b45c748f0136b493d8ee6426f2857a08be7 Mon Sep 17 00:00:00 2001 From: easyone Date: Tue, 17 Dec 2024 10:09:26 +0900 Subject: [PATCH 381/396] Fix: Fix line break. --- .../easyone-jwlee.go | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go b/construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go index 5269e214e..231f2c1e8 100644 --- a/construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/easyone-jwlee.go @@ -10,15 +10,6 @@ // SC // map O(n) + 재귀함수 최악의 경우 한쪽으로만 노드가 이어지는 경우 O(n) = O(n) -/** - * Definition for a binary tree node. - * type TreeNode struct { - * Val int - * Left *TreeNode - * Right *TreeNode - * } - */ - func buildTree(preorder []int, inorder []int) *TreeNode { inorderMap := make(map[int]int) for i, n := range inorder { @@ -47,4 +38,3 @@ func buildTree(preorder []int, inorder []int) *TreeNode { return recursive(0, 0, len(inorder)-1) } - \ No newline at end of file From 568c58727d6c4660f3d600b2068b83834dca0389 Mon Sep 17 00:00:00 2001 From: GangBean Date: Tue, 17 Dec 2024 19:19:49 +0900 Subject: [PATCH 382/396] feat: solve 3sum --- 3sum/GangBean.java | 48 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 3sum/GangBean.java diff --git a/3sum/GangBean.java b/3sum/GangBean.java new file mode 100644 index 000000000..a5c23dd9a --- /dev/null +++ b/3sum/GangBean.java @@ -0,0 +1,48 @@ +class Solution { + public List> threeSum(int[] nums) { + /** + 1. understanding + - integer array nums, find the whole combination of 3 nums, and the sum of the 3 nums equal to 0. And don't allow reusing same indiced number(but can duplicate in value) + 2. solve strategy + - brute force + - in every combination, validate sum of the nums equal to 0 + - but it can take O(N^3) times where N is the length of input array, and given that the N can be 3000 at most(3 * 10^3), time can be 27 * 10^9, which takes too long... + - sort and two pointers + - sort nums in ascending order, so move the left pointer to right means the sum of window is getting bigger. + - and mid pointer set to left + 1 index + - if sum of pointers is less than 0, then move mid pointer to right, until the sum is bigger than 0, and while processing them, if the sum of pointers is 0, then add the combination to the return list. + - [-4, -1, -1, 0, 1, 2]: + + 3. complexity + - time: O(N^2) -> each left pointer, you can search at most N-1, and left pointer's range is [0, N-1), so the max length is N-1 for left index pointer. + - space: O(1) -> no extra space is needed + */ + // 0. assign return variable Set + Set> answer = new HashSet<>(); + + // 1. sort the num array in ascending order + Arrays.sort(nums); // O(NlogN) + // Arrays.stream(nums).forEach(System.out::println); + + // 3. move the mid pointer from left to right to find the combination of which's sum is 0, and if the sum is over 0, and then move right pointer to the left. else if the sum is under 0, then move left pointer to right direction. + for (int left = 0; left < nums.length - 1; left++) { + int mid = left + 1; + int right = nums.length - 1; + while (mid < right) { + // System.out.println(String.format("%d,%d,%d", nums[left], nums[mid], nums[right])); + int sum = nums[left] + nums[mid] + nums[right]; + if (sum > 0) { + right--; + } else if (sum == 0) { + answer.add(List.of(nums[left], nums[mid], nums[right])); + right--; + } else { + mid++; + } + } + } + + return new ArrayList<>(answer); + } +} + From bfc2cb1b40033b91ce772943b18319d238232784 Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Tue, 17 Dec 2024 12:54:25 -0800 Subject: [PATCH 383/396] update --- top-k-frequent-elements/EstherKim97.py | 1 + 1 file changed, 1 insertion(+) diff --git a/top-k-frequent-elements/EstherKim97.py b/top-k-frequent-elements/EstherKim97.py index 54821d78e..ebea89889 100644 --- a/top-k-frequent-elements/EstherKim97.py +++ b/top-k-frequent-elements/EstherKim97.py @@ -15,3 +15,4 @@ def topKFrequent(self, nums, k): return [x[1] for x in data[:k]] #nums.count(i) + From 2a015b542f97b237e462e0a5ad882899153c0df9 Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Tue, 17 Dec 2024 12:55:13 -0800 Subject: [PATCH 384/396] update --- contains-duplicate/EstherKim97.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contains-duplicate/EstherKim97.py b/contains-duplicate/EstherKim97.py index 60dad6f0c..e88ccb839 100644 --- a/contains-duplicate/EstherKim97.py +++ b/contains-duplicate/EstherKim97.py @@ -6,4 +6,5 @@ def containsDuplicate(nums): if num in seen: return True seen.add(num) - return False \ No newline at end of file + return False + From 79680f380661c447ff8b58df098efdfcbe07d58f Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Tue, 17 Dec 2024 12:58:58 -0800 Subject: [PATCH 385/396] update --- valid-palindrome/EstherKim97.py | 1 + 1 file changed, 1 insertion(+) diff --git a/valid-palindrome/EstherKim97.py b/valid-palindrome/EstherKim97.py index 4accf4e50..4630ab127 100644 --- a/valid-palindrome/EstherKim97.py +++ b/valid-palindrome/EstherKim97.py @@ -9,3 +9,4 @@ def isPalindrome(self, s): if s[i] != s[-(i+1)]: return False return True + From 8f0d275cf06d0f1e7526311f294fb412121c3b47 Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Tue, 17 Dec 2024 13:01:18 -0800 Subject: [PATCH 386/396] updatE --- top-k-frequent-elements/EstherKim97.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/top-k-frequent-elements/EstherKim97.py b/top-k-frequent-elements/EstherKim97.py index ebea89889..a1a3e8ad0 100644 --- a/top-k-frequent-elements/EstherKim97.py +++ b/top-k-frequent-elements/EstherKim97.py @@ -13,6 +13,4 @@ def topKFrequent(self, nums, k): data = sorted(data, reverse=True, key=lambda x:[1]) return [x[1] for x in data[:k]] - - #nums.count(i) - + \ No newline at end of file From f445f712f26cfc5e57da3a1d6634aebb6ea9b087 Mon Sep 17 00:00:00 2001 From: Esther <181283957+EstherKim97@users.noreply.github.com> Date: Tue, 17 Dec 2024 13:03:23 -0800 Subject: [PATCH 387/396] update --- top-k-frequent-elements/EstherKim97.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/top-k-frequent-elements/EstherKim97.py b/top-k-frequent-elements/EstherKim97.py index a1a3e8ad0..cef0b6cd7 100644 --- a/top-k-frequent-elements/EstherKim97.py +++ b/top-k-frequent-elements/EstherKim97.py @@ -13,4 +13,4 @@ def topKFrequent(self, nums, k): data = sorted(data, reverse=True, key=lambda x:[1]) return [x[1] for x in data[:k]] - \ No newline at end of file + From fb2233a9c232ec4f4578863a3b60a17fe64f7f60 Mon Sep 17 00:00:00 2001 From: SooJeong Han <105469888+hancrysta1@users.noreply.github.com> Date: Wed, 18 Dec 2024 13:24:14 +0900 Subject: [PATCH 388/396] Update sj.java --- top-k-frequent-elements/sj.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/top-k-frequent-elements/sj.java b/top-k-frequent-elements/sj.java index 0fba33de1..dab94ffa5 100644 --- a/top-k-frequent-elements/sj.java +++ b/top-k-frequent-elements/sj.java @@ -14,4 +14,4 @@ public int[] topKFrequent(int[] nums, int k) { return answer; } -} \ No newline at end of file +} From ba795a0c1367918f87e1e690479c9d5c90ae6daa Mon Sep 17 00:00:00 2001 From: SooJeong Han <105469888+hancrysta1@users.noreply.github.com> Date: Wed, 18 Dec 2024 13:24:56 +0900 Subject: [PATCH 389/396] Update sj.java --- contains-duplicate/sj.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contains-duplicate/sj.java b/contains-duplicate/sj.java index b0838e3f0..9a9e3cfc6 100644 --- a/contains-duplicate/sj.java +++ b/contains-duplicate/sj.java @@ -5,4 +5,4 @@ public boolean containsDuplicate(int[] nums) { if(numSet.size()!=nums.length) return true; else return false; } -} \ No newline at end of file +} From 8471fa09380a9678f412159840d8896b3bad15b4 Mon Sep 17 00:00:00 2001 From: SooJeong Han <105469888+hancrysta1@users.noreply.github.com> Date: Wed, 18 Dec 2024 13:25:07 +0900 Subject: [PATCH 390/396] Update sj.java --- valid-palindrome/sj.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/valid-palindrome/sj.java b/valid-palindrome/sj.java index 96012eab1..627b4aa76 100644 --- a/valid-palindrome/sj.java +++ b/valid-palindrome/sj.java @@ -15,4 +15,4 @@ public boolean isPalindrome(String s) { } return true; } -} \ No newline at end of file +} From dedce64983deffa663d60532aadb38377eb6b888 Mon Sep 17 00:00:00 2001 From: SooJeong Han <105469888+hancrysta1@users.noreply.github.com> Date: Wed, 18 Dec 2024 13:28:12 +0900 Subject: [PATCH 391/396] Rename sj.java to hancrysta1.java --- top-k-frequent-elements/{sj.java => hancrysta1.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename top-k-frequent-elements/{sj.java => hancrysta1.java} (100%) diff --git a/top-k-frequent-elements/sj.java b/top-k-frequent-elements/hancrysta1.java similarity index 100% rename from top-k-frequent-elements/sj.java rename to top-k-frequent-elements/hancrysta1.java From 86f27dcc885ec48c4a17dba11d94a0292825ecd9 Mon Sep 17 00:00:00 2001 From: SooJeong Han <105469888+hancrysta1@users.noreply.github.com> Date: Wed, 18 Dec 2024 13:28:31 +0900 Subject: [PATCH 392/396] Rename sj.java to hancrysta1.java --- contains-duplicate/{sj.java => hancrysta1.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contains-duplicate/{sj.java => hancrysta1.java} (100%) diff --git a/contains-duplicate/sj.java b/contains-duplicate/hancrysta1.java similarity index 100% rename from contains-duplicate/sj.java rename to contains-duplicate/hancrysta1.java From 6f49d2a00231b02453640c3056eb45698f126beb Mon Sep 17 00:00:00 2001 From: SooJeong Han <105469888+hancrysta1@users.noreply.github.com> Date: Wed, 18 Dec 2024 13:29:01 +0900 Subject: [PATCH 393/396] Rename sj.java to hancrysta1.java --- valid-palindrome/{sj.java => hancrysta1.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename valid-palindrome/{sj.java => hancrysta1.java} (100%) diff --git a/valid-palindrome/sj.java b/valid-palindrome/hancrysta1.java similarity index 100% rename from valid-palindrome/sj.java rename to valid-palindrome/hancrysta1.java From df74dd463c9845e47c35a3f925cc9aafb0023a4e Mon Sep 17 00:00:00 2001 From: easyone Date: Thu, 19 Dec 2024 10:45:05 +0900 Subject: [PATCH 394/396] Feat: Add solution of decode-ways --- decode-ways/easyone-jwlee.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 decode-ways/easyone-jwlee.go diff --git a/decode-ways/easyone-jwlee.go b/decode-ways/easyone-jwlee.go new file mode 100644 index 000000000..29e7f85af --- /dev/null +++ b/decode-ways/easyone-jwlee.go @@ -0,0 +1,33 @@ +// 풀이 +// dp로 풀이 +// 두자리 수에 적합하면 prev2(i-2)에 해당하는 값을 더하기 + +// TC +// O(n) + +// SC +// data type이 int인 변수만 사용했으므로 O(1) + +func numDecodings(s string) int { + if len(s) == 0 || s[0] == '0' { + return 0 + } + prev2, prev1 := 1, 1 + for i := 1; i < len(s); i++ { + curr := 0 + + // 한자리수 확인 + if s[i] != '0' { + curr += prev1 + } + + // 두자리수 확인 + digit, _ := strconv.Atoi(s[i-1 : i+1]) + if digit >= 10 && digit <= 26 { + curr += prev2 + } + + prev2, prev1 = prev1, curr + } + return prev1 +} From 79a9c93c5800e88ca5892ec57459b45bf4a90007 Mon Sep 17 00:00:00 2001 From: GangBean Date: Thu, 19 Dec 2024 20:17:12 +0900 Subject: [PATCH 395/396] feat: solve construct binary tree from prorder and inorder traversal --- .../GangBean.java | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 construct-binary-tree-from-preorder-and-inorder-traversal/GangBean.java diff --git a/construct-binary-tree-from-preorder-and-inorder-traversal/GangBean.java b/construct-binary-tree-from-preorder-and-inorder-traversal/GangBean.java new file mode 100644 index 000000000..57afaef4a --- /dev/null +++ b/construct-binary-tree-from-preorder-and-inorder-traversal/GangBean.java @@ -0,0 +1,51 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ +class Solution { + public TreeNode buildTree(int[] preorder, int[] inorder) { + /** + 1. understanding + - preorder: mid -> left -> right + - inorder: left -> mid -> right + - so, first element of the preorder array is always mid node. + - if the idx of inorder's 1st depth mid node is k, then inorder[0:k-1] is the left tree part array. And also, preorder[k:] is the right tree part. + 2. strategy + - find the inorder's mid node idx, and then split left tree part and right part, buildTree with each preorder and inorder part. + + 3. complexity + - time: O(N^2) + - space: O(N^2) + */ + if (preorder.length == 0) return null; + if (preorder.length == 1) return new TreeNode(preorder[0]); + int i = 0; + List leftPreorder = new ArrayList<>(); // O(N) + List leftInorder = new ArrayList<>(); // O(N) + List rightPreorder = new ArrayList<>(); // O(N) + List rightInorder = new ArrayList<>(); // O(N) + for (; i < inorder.length; i++) { // O(N) + if (inorder[i] == preorder[0]) break; + leftPreorder.add(preorder[i+1]); + leftInorder.add(inorder[i]); + } + for (int idx = i+1; idx < inorder.length; idx++) { // O(N) + rightPreorder.add(preorder[idx]); + rightInorder.add(inorder[idx]); + } + + return new TreeNode(preorder[0], buildTree(leftPreorder.stream().mapToInt(Integer::intValue).toArray(), leftInorder.stream().mapToInt(Integer::intValue).toArray()), buildTree(rightPreorder.stream().mapToInt(Integer::intValue).toArray(), rightInorder.stream().mapToInt(Integer::intValue).toArray())); + } +} + From 1654d1dbabb00816869f1be803d68b3309610011 Mon Sep 17 00:00:00 2001 From: GangBean Date: Fri, 20 Dec 2024 04:01:12 +0900 Subject: [PATCH 396/396] feat: solve decode ways --- decode-ways/GangBean.java | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 decode-ways/GangBean.java diff --git a/decode-ways/GangBean.java b/decode-ways/GangBean.java new file mode 100644 index 000000000..849cac51b --- /dev/null +++ b/decode-ways/GangBean.java @@ -0,0 +1,45 @@ +class Solution { + public int numDecodings(String s) { + /** + 1. understanding + - number to upper case alphabet mapping code: 1 -> A, ... 26 -> Z + - many ways to decode each input string + - also there can be no way to decode input string. + - answer fits in 32-bit integer. + + 2. example + - 12: (1, 2), (12) + - 226: (2, 2, 6), (2, 26), (22, 6) + - 06: (0, x) + + 3. strategy + - iterate in reverse order, + - at index k, dp[k] means the count of decode ways till that index. + - dp[k-1] = 0 if num[k] == 0 + - dp[k-1] = dp[k] + dp[k+1] if 1<= nums[k-1:k] < 27 + - dp[k-1] = dp[k] + - dp[n] = 1 -> assume that first empty input can be decoded in 1 way. + + 4. complexity + - time: O(N) + - space: O(1) + */ + int prev = 1; + int current = 1; + for (int i = s.length()-1; i >= 0; i--) { // O(1) + if (s.charAt(i) == '0') { + int tmp = current; + current = 0; + prev = tmp; + } else if ( (i+1) < s.length() && Integer.parseInt(s.substring(i, i+2)) < 27) { + int tmp = current; + current = prev + current; + prev = tmp; + } else { + prev = current; + } + } + return current; + } +} +