Skip to content

Commit

Permalink
Merge pull request #783 from changchanghwang/main
Browse files Browse the repository at this point in the history
[Arthur] Week 3
  • Loading branch information
changchanghwang authored Dec 28, 2024
2 parents 1ab3fe4 + 4d19802 commit 5d19a8c
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
26 changes: 26 additions & 0 deletions product-of-array-except-self/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// time complexity: O(n)
// space complexity: O(1)
// prefix와 postfix를 이용하여 계산
// 예를 들어, [1, 2, 3, 4] 일 때,
// prefix는 [1, 1, 2, 6] 이고 postfix는 [24, 12, 4, 1] 이다.
// 그리고 서로 곱하면 [24, 12, 8, 6] 이 된다.
func productExceptSelf(nums []int) []int {
res := make([]int, len(nums))
for i := range res {
res[i] = 1
}

prefix := 1
for i := 0; i < len(nums); i++ {
res[i] = prefix
prefix *= nums[i]
}

postfix := 1
for i := len(nums) - 1; i >= 0; i-- {
res[i] *= postfix
postfix *= nums[i]
}

return res
}
6 changes: 6 additions & 0 deletions reverse-bits/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// Time Complexity: O(1)
// Space Complexity: O(1)
func reverseBits(num uint32) uint32 {
reversedBits := bits.Reverse32(num)
return reversedBits
}
15 changes: 15 additions & 0 deletions two-sum/changchanghwang.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Time: O(n)
// Space: O(n)
func twoSum(nums []int, target int) []int {
m := make(map[int]int)

// O(n)
for i, num := range nums {
// O(1)
if j, ok := m[target-num]; ok && j != i { // target = num2 + num1 -> num2 = target - num1 을 이용하여 두 수를 찾는다.
return []int{j, i}
}
m[num] = i // 없다면 현재 수를 키로 하여 인덱스를 저장한다.
}
return nil
}

0 comments on commit 5d19a8c

Please sign in to comment.