Skip to content

[Arthur] Week 1 #626

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 12 commits into from
Dec 10, 2024
15 changes: 15 additions & 0 deletions contains-duplicate/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// 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 {
if hashMap[num] {
return true
}
hashMap[num] = true
}
return false
}
14 changes: 14 additions & 0 deletions house-robber/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -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
}
34 changes: 34 additions & 0 deletions longest-consecutive-sequence/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -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
}
29 changes: 29 additions & 0 deletions top-k-frequent-elements/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// 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 {
hashMap[num]++
}

result := [][]int{}

for num, count := range hashMap {
result = append(result, []int{num, count})
}

sort.Slice(result, func(i, j int) bool { // go의 sort는 quicksort를 기본적으로 사용한다. O(nlogn)
return result[i][1] > result[j][1]
})
Comment on lines +19 to +21
Copy link
Contributor

Choose a reason for hiding this comment

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

go를 처음 본 입장에서, sort 알고리즘 주석 넣으신 부분 도움되네요.
감사합니다.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

하핳.. 저도 궁금해서 찾아봤는데 저렇다고 하더라구요 ㅎㅎ..


resultNums := make([]int, 0, k)
for i := 0; i < k; i++ {
resultNums = append(resultNums, result[i][0])
}

return resultNums
}
38 changes: 38 additions & 0 deletions valid-palindrome/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// 풀이
// alphabet, number만 걸러내서 소문자로 바꾼 후 reverse한 문자열, 걸러낸 문자열과 비교하여 같은지 확인한다.

// O(n) time complexity
// 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 lowerCaseString {
if regex.MatchString(string(char)) {
reverseAndFilteredString = c + reverseAndFilteredString
filteredString += c
Comment on lines +15 to +16
Copy link
Contributor

Choose a reason for hiding this comment

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

제가 알기로는 strings 패키지의 strings.Builder struct를 사용하는 것이 더 효과적인 것으로 알고 있습니다 :)
참고링크

Copy link
Contributor Author

Choose a reason for hiding this comment

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

오... 제가 고퍼가 된지 얼마 되지 않아 몰랐습니다!! 수정했습니다. 다만 reverseAndFilteredString의 경우 strings.Builder를 사용하게되면 로직이 조금더 복잡해지기도 하고 가독성이 조금 안좋아지지 않을까 하여 filteredString만 수정했습니다 :)

}
}

return reverseAndFilteredString == filteredString
}

// O(n) time complexity
// O(n) space complexity
func isPalindrome2(s string) bool {
lowerCaseString := strings.ToLower(s)
reverseAndFilteredString := ""
var filteredString strings.Builder

for _, char := range lowerCaseString {
if unicode.IsLetter(char) || unicode.IsDigit(char) {
reverseAndFilteredString = string(char) + reverseAndFilteredString
filteredString.WriteRune(char)
}
}

return reverseAndFilteredString == filteredString.String()
}
Loading