diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 000000000..bb150a630 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,54 @@ +name: Build my gitbook and deploy to gh-pages + +on: + workflow_dispatch: + push: + branches: + - master + +jobs: + master-to-gh-pages: + runs-on: ubuntu-latest + + steps: + - name: checkout master + uses: actions/checkout@v2 + with: + submodules: recursive + ref: master + + - name: install nodejs + uses: actions/setup-node@v3 + with: + node-version: 10.14.1 + + - name: configue gitbook + run: | + npm install + npm install -g gitbook-cli + gitbook install + npm install -g gitbook-summary + + - name: generate _book folder + run: | + book sm + ln -s -f SUMMARY.md Content.md + gitbook build + cp SUMMARY.md _book + + - name: push _book to branch gh-pages + env: + TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} + REF: github.com/${{github.repository}} + MYEMAIL: kimi0230@gmail.com + MYNAME: ${{github.repository_owner}} + run: | + cd _book + git config --global user.email "${MYEMAIL}" + git config --global user.name "${MYNAME}" + git init + git remote add origin https://${REF} + git add . + git commit -m "Updated By Github Actions With Build ${{github.run_number}} of ${{github.workflow}} For Github Pages" + git branch -M master + git push --force --quiet "https://${TOKEN}@${REF}" master:gh-pages diff --git a/.github/workflows/releace.yml b/.github/workflows/releace.yml new file mode 100644 index 000000000..32839eec7 --- /dev/null +++ b/.github/workflows/releace.yml @@ -0,0 +1,75 @@ +name: Build latest tag + +on: + workflow_dispatch: + push: + tags: + - "v*.*.*" + +jobs: + build: + name: Build + runs-on: macos-latest + steps: + - name: checkout master + uses: actions/checkout@v2 + with: + submodules: recursive + ref: master + + - name: install nodejs + uses: actions/setup-node@v1 + + - name: install calibre + run: | + brew install calibre + + - name: configue gitbook + run: | + npm install -g gitbook-cli + gitbook install + npm install -g gitbook-summary + + - name: generate pdf file + run: | + book sm + ln -s -f SUMMARY.md README.md + gitbook pdf + gitbook epub + gitbook mobi + mkdir -p path/to/artifact + cp book.pdf path/to/artifact + cp book.epub path/to/artifact + cp book.mobi path/to/artifact + + - name: Upload file + uses: actions/upload-artifact@v2 + with: + name: book.pdf + path: path/to/artifact/book.pdf + + - name: Download file + id: download + uses: actions/download-artifact@v2 + with: + name: book.pdf + path: path/to/artifact + + - name: Display structure of downloaded files + run: ls -R + working-directory: path/to/artifact + + - name: 'Echo download path' + run: echo ${{steps.download.outputs.download-path}} + + - name: Release + uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') + with: + files: | + path/to/artifact/book.pdf + path/to/artifact/book.epub + path/to/artifact/book.mobi + LICENSE + env: + GITHUB_TOKEN: ${{ secrets.GH_ACCESS_TOKEN }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..6cc51ba2e --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +_book +node_modules +.obsidian/* \ No newline at end of file diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..e69de29bb diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 000000000..608d3c699 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Launch Package", + "type": "go", + "request": "launch", + "mode": "auto", + "program": "${fileDirname}" + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..52a988850 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "vue.features.codeActions.enable": false +} \ No newline at end of file diff --git a/Algorithms/A1B2C3/a1b2c3.go b/Algorithms/A1B2C3/a1b2c3.go new file mode 100644 index 000000000..0bb37d4d1 --- /dev/null +++ b/Algorithms/A1B2C3/a1b2c3.go @@ -0,0 +1,80 @@ +package a1b2c3 + +import ( + "sync" +) + +func ChannelWBuffer() { + abc := make(chan struct{}, 1) + num := make(chan struct{}, 1) + done := make(chan struct{}) + abc <- struct{}{} + + go func() { + for i := 65; i <= 90; i++ { + <-abc + // fmt.Printf("%v", string(rune(i))) + num <- struct{}{} + } + }() + go func() { + for i := 1; i <= 26; i++ { + <-num + // fmt.Printf("%v", i) + abc <- struct{}{} + } + done <- struct{}{} + }() + // time.Sleep(1 * time.Second) + <-done +} + +func ChannelWOBuffer() { + abc := make(chan struct{}) + num := make(chan struct{}) + done := make(chan struct{}) + + go func() { + for i := 65; i <= 90; i++ { + // fmt.Printf("%v", string(rune(i))) + abc <- struct{}{} + <-num + } + }() + go func() { + for i := 1; i <= 26; i++ { + <-abc + // fmt.Printf("%v", i) + num <- struct{}{} + } + done <- struct{}{} + }() + // time.Sleep(1 * time.Second) + <-done +} + +func WGLock() { + abcMux := sync.Mutex{} + numMux := sync.Mutex{} + + numMux.Lock() + wg := sync.WaitGroup{} + wg.Add(2) + go func() { + defer wg.Done() + for i := 65; i <= 90; i++ { + abcMux.Lock() + // fmt.Printf("%v", string(rune(i))) + numMux.Unlock() + } + }() + go func() { + defer wg.Done() + for i := 1; i <= 26; i++ { + numMux.Lock() + // fmt.Printf("%v", i) + abcMux.Unlock() + } + }() + wg.Wait() +} diff --git a/Algorithms/A1B2C3/a1b2c3_test.go b/Algorithms/A1B2C3/a1b2c3_test.go new file mode 100644 index 000000000..f2f18c13a --- /dev/null +++ b/Algorithms/A1B2C3/a1b2c3_test.go @@ -0,0 +1,48 @@ +package a1b2c3 + +import "testing" + +func TestChannelWBuffer(t *testing.T) { + ChannelWBuffer() +} + +func TestChannelWOBuffer(t *testing.T) { + ChannelWOBuffer() +} +func TestWGLock(t *testing.T) { + WGLock() +} + +func BenchmarkChannelWBuffer(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ChannelWBuffer() + } +} + +func BenchmarkChannelWOBuffer(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ChannelWOBuffer() + } +} + +func BenchmarkWGLock(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + WGLock() + } +} + +// go test -benchmem -run=none LeetcodeGolang/Algorithms/A1B2C3 -bench=. +/* +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Algorithms/A1B2C3 +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkChannelWBuffer-4 79159 14612 ns/op 344 B/op 5 allocs/op +BenchmarkChannelWOBuffer-4 83068 14451 ns/op 344 B/op 5 allocs/op +BenchmarkWGLock-4 51303 23072 ns/op 96 B/op 5 allocs/op +PASS +ok LeetcodeGolang/Algorithms/A1B2C3 4.092s +*/ diff --git a/Algorithms/A1B2C3/index.html b/Algorithms/A1B2C3/index.html new file mode 100644 index 000000000..6665db74a --- /dev/null +++ b/Algorithms/A1B2C3/index.html @@ -0,0 +1,3827 @@ + + + + + + + A1B2C3: Two Go Routine Print A1B2C3....Z26 ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ + + + + + + + +
+ +
+ +
+ + + + + + + + +
+
+ +
+
+ +
+ +

A1B2C3

用兩個 go routine 印出 A1B2C3....Z26 +Two Go Routine Print A1B2C3....Z26

+

Channle With Buffer

+
func ChannelWBuffer() {
+    abc := make(chan struct{}, 1)
+    num := make(chan struct{}, 1)
+    done := make(chan struct{})
+    abc 
+

Channel Without Buffer

+
func ChannelWOBuffer() {
+    abc := make(chan struct{})
+    num := make(chan struct{})
+    done := make(chan struct{})
+
+    go func() {
+        for i := 65; i 
+

Wait Group

+

+func WGLock() {
+    abcMux := sync.Mutex{}
+    numMux := sync.Mutex{}
+
+    numMux.Lock()
+    wg := sync.WaitGroup{}
+    wg.Add(2)
+    go func() {
+        defer wg.Done()
+        for i := 65; i 
+

Benchmark

+
goos: darwin
+goarch: amd64
+pkg: LeetcodeGolang/Algorithms/A1B2C3
+cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
+BenchmarkChannelWBuffer-4          79159             14612 ns/op             344 B/op          5 allocs/op
+BenchmarkChannelWOBuffer-4         83068             14451 ns/op             344 B/op          5 allocs/op
+BenchmarkWGLock-4                  51303             23072 ns/op              96 B/op          5 allocs/op
+PASS
+ok      LeetcodeGolang/Algorithms/A1B2C3        4.092s
+
+
© Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
+ +
+ +
+
+
+ +

results matching ""

+
    + +
    +
    + +

    No results matching ""

    + +
    +
    +
    + +
    +
    + +
    + + + + + + +
    + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Algorithms/Find_Target_Last_Index/findtargetlastindex.go b/Algorithms/Find_Target_Last_Index/findtargetlastindex.go new file mode 100644 index 000000000..86a57ed4c --- /dev/null +++ b/Algorithms/Find_Target_Last_Index/findtargetlastindex.go @@ -0,0 +1,50 @@ +package findtargetlastindex + +// RightBound, ๆœ‰้ปž้กžไผผ nums ๅคงๆ–ผ target็š„ๅ…ƒ็ด ๆœ‰ๅนพๅ€‹ + +// ไบŒๅˆ†ๆœๅฐ‹ +func Solution(nums []int, target int) int { + + left, right := 0, len(nums)-1 + + for left <= right { + mid := int(uint(left+right) >> 1) + if nums[mid] == target { + if nums[right] == target { + return right + } else { + right-- + } + } else if nums[mid] < target { + left = mid + 1 + } else { + right = mid - 1 + } + } + return -1 +} + +func SolutionRecursive(nums []int, target int) int { + left, right := 0, len(nums)-1 + return findTarget(nums, left, right, target) +} + +func findTarget(nums []int, left, right, target int) int { + if left > right { + return -1 + } + + mid := int(uint(left+right) >> 1) + if nums[mid] == target { + if nums[right] == target { + return right + } else { + return findTarget(nums, mid, right-1, target) + } + } else if nums[mid] < target { + return findTarget(nums, mid+1, right, target) + } else { + return findTarget(nums, left, mid-1, target) + } + +} diff --git a/Algorithms/Find_Target_Last_Index/findtargetlastindex.html b/Algorithms/Find_Target_Last_Index/findtargetlastindex.html new file mode 100644 index 000000000..b53cdd913 --- /dev/null +++ b/Algorithms/Find_Target_Last_Index/findtargetlastindex.html @@ -0,0 +1,3902 @@ + + + + + + + Find Target Last Index ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + +
    + +
    + +
    + + + + + + + + +
    +
    + +
    +
    + +
    + +

    Find Target Last Index

    在有序的array中 找出target在array中最後的index是什麼 +用二分搜尋法去找, RightBound

    +

    可參考

    +

    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0704.Binary-Search/main.go

    +

    方法一

    +
    func Solution(nums []int, target int) int {
    +    left, right := 0, len(nums)-1
    +    result := -1
    +    for left <= right="" {="" mid="" :="int(uint(right+left)">> 1)
    +        if nums[mid] == target {
    +            // 繼續找, 縮小右邊
    +            if target == nums[right] {
    +                result = right
    +                break
    +            } else {
    +                right--
    +            }
    +        } else if nums[mid] < target {
    +            // 往右找
    +            left = mid + 1
    +        } else if nums[mid] > target {
    +            // 往左找
    +            right = mid - 1
    +        }
    +    }
    +    return result
    +}
    +
    +
    +

    方法二 遞迴

    +
    func SolutionRecursive(nums []int, target int) int {
    +    left, right := 0, len(nums)-1
    +    return findTarget(nums, left, right, target)
    +}
    +
    +func findTarget(nums []int, left, right, target int) int {
    +    if left > right {
    +        return -1
    +    }
    +
    +    mid := int(uint(left+right) >> 1)
    +    if nums[mid] == target {
    +        if nums[right] == target {
    +            return right
    +        } else {
    +            return findTarget(nums, mid, right-1, target)
    +        }
    +    } else if nums[mid] < target {
    +        return findTarget(nums, mid+1, right, target)
    +    } else {
    +        return findTarget(nums, left, mid-1, target)
    +    }
    +
    +}
    +
    +
    go test -benchmem -run=none LeetcodeGolang/Algorithms/Find_Target_Last_Index -bench=.
    +goos: darwin
    +goarch: amd64
    +pkg: LeetcodeGolang/Algorithms/Find_Target_Last_Index
    +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
    +BenchmarkSolution-8             54216429                24.75 ns/op            0 B/op          0 allocs/op
    +BenchmarkSolutionRecursive-8    40756744                27.75 ns/op            0 B/op          0 allocs/op
    +PASS
    +ok      LeetcodeGolang/Algorithms/Find_Target_Last_Index        2.537s
    +
    +
    +

    RightBound

    +
    // 有點類似 nums 大於 target的元素有幾個
    +func RightBound(nums []int, target int) (index int) {
    +    lenght := len(nums)
    +    if lenght <= 0="" {="" return="" -1="" }="" left,="" right="" :="0," lenght-1="" for="" left="" <="right" ้™คไปฅ2="" mid="" +="" (right-left)="">>1
    +        mid := int(uint(right+left) >> 1)
    +        if nums[mid] == target {
    +            // 注意:要繼續找右邊, 所以把左邊變大=mid+1
    +            left = mid + 1
    +        } else if nums[mid] < target {
    +            // 找右邊
    +            left = mid + 1
    +        } else if nums[mid] > target {
    +            // 找左邊
    +            right = mid - 1
    +        }
    +    }
    +    // 都沒找到 注意:right越界情況
    +    if right < 0 || nums[right] != target {
    +        return -1
    +    }
    +    return right
    +}
    +
    +

    LeftBound

    +
    // 有點類似 nums 小於 target的元素有幾個
    +func LeftBound(nums []int, target int) (index int) {
    +    lenght := len(nums)
    +    if lenght <= 0="" {="" return="" -1="" }="" left,="" right="" :="0," lenght-1="" for="" left="" <="right" ้™คไปฅ2="" mid="" +="" (right-left)="">>1
    +        mid := int(uint(right+left) >> 1)
    +        if nums[mid] == target {
    +            // 要繼續找左邊, 所以把右邊變小
    +            right = mid - 1
    +        } else if nums[mid] < target {
    +            // 找右邊
    +            left = mid + 1
    +        } else if nums[mid] > target {
    +            // 找左邊
    +            right = mid - 1
    +        }
    +    }
    +    // 都沒找到 注意: left越界情況
    +    if left >= lenght || nums[left] != target {
    +        return -1
    +    }
    +    return left
    +}
    +
    +
    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
    + +
    + +
    +
    +
    + +

    results matching ""

    +
      + +
      +
      + +

      No results matching ""

      + +
      +
      +
      + +
      +
      + +
      + + + + + + +
      + + +
      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Algorithms/Find_Target_Last_Index/findtargetlastindex_test.go b/Algorithms/Find_Target_Last_Index/findtargetlastindex_test.go new file mode 100644 index 000000000..d5ae6f89c --- /dev/null +++ b/Algorithms/Find_Target_Last_Index/findtargetlastindex_test.go @@ -0,0 +1,98 @@ +package findtargetlastindex + +import "testing" + +var tests = []struct { + arg1 []int + arg2 int + want int +}{ + { + []int{1, 2, 3, 4, 5, 6, 6, 6, 9}, + 6, + 7, + }, + { + []int{1, 2, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 8, 9, 9, 9, 9}, + 6, + 12, + }, + { + []int{1, 2, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 7, 8, 9, 9, 9, 9}, + 5, + 6, + }, + { + []int{5, 7, 7, 8, 8, 10}, + 8, + 4, + }, + { + []int{5, 7, 7, 8, 8, 10}, + 6, + -1, + }, + { + []int{1, 2, 3, 4, 5}, + 3, + 2, + }, + { + []int{1, 2, 3, 4, 5}, + 5, + 4, + }, + {[]int{1, 2, 3, 4, 5}, + 0, + -1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolutionRecursive(t *testing.T) { + for _, tt := range tests { + // start := 0 + // end := len(tt.arg1) - 1 + if got := SolutionRecursive(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + + // SolutionRecursive(tt.arg1, start, end, tt.arg2) + } +} + +func BenchmarkSolution(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + for _, tt := range tests { + Solution(tt.arg1, tt.arg2) + } + } +} +func BenchmarkSolutionRecursive(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + for _, tt := range tests { + SolutionRecursive(tt.arg1, tt.arg2) + } + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Algorithms/Find_Target_Last_Index -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Algorithms/Find_Target_Last_Index +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkSolution-8 54216429 24.75 ns/op 0 B/op 0 allocs/op +BenchmarkSolutionRecursive-8 40756744 27.75 ns/op 0 B/op 0 allocs/op +PASS +ok LeetcodeGolang/Algorithms/Find_Target_Last_Index 2.537s +*/ diff --git a/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/index.html b/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/index.html new file mode 100644 index 000000000..a6d3327d1 --- /dev/null +++ b/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/index.html @@ -0,0 +1,3838 @@ + + + + + + + Intersection Of Two Sorted Arrays Using In Place Approach ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
      +
      + + + + + + + + +
      + +
      + +
      + + + + + + + + +
      +
      + +
      +
      + +
      + +

      Intersection of Two Sorted Arrays using In Place Approach

      Intersection of Two Sorted Arrays using In Place Approach

      +

      要在原地(in-place)解決這個問題,可以使用雙指針的方法。假設給定的兩個數組分別為A和B,它們已經按升序排序。

      +

      首先,我們可以初始化兩個指針i和j分別指向A和B的起始位置,然後開始進行比較。如果A[i]小於B[j],則移動指針i向後移動一位;如果A[i]大於B[j],則移動指針j向後移動一位;如果A[i]等於B[j],則將該值添加到結果中,並將兩個指針都向後移動一位。

      +

      重複上述步驟,直到其中一個數組的指針達到數組末尾為止。最終,得到的結果就是兩個數組的交集。

      +
      package intersection
      +
      +func FindIntersection(A, B []int) []int {
      +    var i, j int = 0, 0
      +    result := []int{}
      +
      +    for i < len(A) && j < len(B) {
      +        if A[i] < B[j] {
      +            i++
      +        } else if A[i] > B[j] {
      +            j++
      +        } else {
      +            result = append(result, A[i])
      +            i++
      +            j++
      +        }
      +    }
      +    return result
      +}
      +
      +
      func TestFindIntersection(t *testing.T) {
      +    var tests = []struct {
      +        arg1 []int
      +        arg2 []int
      +        want []int
      +    }{
      +        {
      +            arg1: []int{1, 3, 4, 6, 7},
      +            arg2: []int{2, 4, 6, 8, 9},
      +            want: []int{4, 6},
      +        },
      +    }
      +
      +    for _, tt := range tests {
      +        if got := FindIntersection(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) {
      +            t.Errorf("got = %v, want = %v", got, tt.want)
      +        }
      +    }
      +}
      +
      +

      TODO: +延伸

      +
        +
      1. 349. Intersection of Two Arrays (easy)
      2. +
      3. 350. Intersection of Two Arrays II
      4. +
      +
      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
      + +
      + +
      +
      +
      + +

      results matching ""

      +
        + +
        +
        + +

        No results matching ""

        + +
        +
        +
        + +
        +
        + +
        + + + + + + +
        + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/intersection.go b/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/intersection.go new file mode 100644 index 000000000..60b892662 --- /dev/null +++ b/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/intersection.go @@ -0,0 +1,19 @@ +package intersection + +func FindIntersection(A, B []int) []int { + var i, j int = 0, 0 + result := []int{} + + for i < len(A) && j < len(B) { + if A[i] < B[j] { + i++ + } else if A[i] > B[j] { + j++ + } else { + result = append(result, A[i]) + i++ + j++ + } + } + return result +} diff --git a/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/intersection_test.go b/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/intersection_test.go new file mode 100644 index 000000000..a757ec2f2 --- /dev/null +++ b/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/intersection_test.go @@ -0,0 +1,26 @@ +package intersection + +import ( + "reflect" + "testing" +) + +func TestFindIntersection(t *testing.T) { + var tests = []struct { + arg1 []int + arg2 []int + want []int + }{ + { + arg1: []int{1, 3, 4, 6, 7}, + arg2: []int{2, 4, 6, 8, 9}, + want: []int{4, 6}, + }, + } + + for _, tt := range tests { + if got := FindIntersection(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Algorithms/SearchGraph/index.html b/Algorithms/SearchGraph/index.html new file mode 100644 index 000000000..0405b1c58 --- /dev/null +++ b/Algorithms/SearchGraph/index.html @@ -0,0 +1,3914 @@ + + + + + + + Search Graph In Golang ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        +
        + + + + + + + + +
        + +
        + +
        + + + + + + + + +
        +
        + +
        +
        + +
        + +

        Search Graph

             2
        +   /   \
        +  /     \
        + 1 - 3 - 5 - 7
        +  \        /
        +   \      6
        +    \   /
        +      4
        +
        +一個Graph,隨便指定一個起點, 優先print出周圍的值
        +
        +// 1 -> [2, 3, 4]
        +// 2 -> [1, 5]
        +// 3 -> [1, 5]
        +// 4 -> [1, 6]
        +// 5 -> [2, 3, 7]
        +// 6 -> [4, 7]
        +// 7 -> [5, 6]
        +// print : 1,2,3,4,5,6,7
        +// Also this is valid : 1,4,3,2,6,5,7
        +
        +例如 開始位置1, print : 1,2,3,4,5,6,
        +
        +

        解法

        +

        用BFS(Queue) +時間複雜度是O(V+E),其中V是圖中節點的數量,E是圖中邊的數量

        +

        解答

        +
        package searchgraph
        +
        +import (
        +    "LeetcodeGolang/Utility/crud"
        +    "LeetcodeGolang/structures"
        +    "fmt"
        +    "strconv"
        +
        +    jsoniter "github.com/json-iterator/go"
        +)
        +
        +func fetchNeighbours(node int) []int {
        +    crud := crud.NewCrud("https://hackbear.tv/graph/" + strconv.Itoa(node))
        +    var result = []int{}
        +
        +    if got := crud.Get(); got.Error != nil {
        +        // fmt.Printf("got = %v", got)
        +    } else {
        +        var json = jsoniter.ConfigCompatibleWithStandardLibrary
        +        json.Unmarshal([]byte(got.Response), &result)
        +    }
        +    return result
        +}
        +
        +/*
        +     2
        +   /   \
        +  /     \
        + 1 - 3 - 5 - 7
        +  \        /
        +   \      6
        +    \   /
        +      4
        +*/
        +
        +// 1 -> [2, 3, 4]
        +// 2 -> [1, 5]
        +// 3 -> [1, 5]
        +// 4 -> [1, 6]
        +// 5 -> [2, 3, 7]
        +// 6 -> [4, 7]
        +// 7 -> [5, 6]
        +// print : 1,2,3,4,5,6,7
        +// Also this is valid : 1,4,3,2,6,5,7
        +
        +// You will be working on this part
        +/*
        +時間複雜度是O(V+E),其中V是圖中節點的數量,E是圖中邊的數量
        +*/
        +func SearchGraph(start int) {
        +    queue := structures.NewQueue()
        +    queue.Push(start)
        +    visit := make(map[int][]int)
        +    for queue.Len() > 0 {
        +        node := queue.Pop()
        +        if _, ok := visit[node]; !ok {
        +            fmt.Printf("%d ", node)
        +            neighours := fetchNeighbours(node)
        +            visit[node] = neighours
        +            for _, neighour := range neighours {
        +                if _, ok := visit[neighour]; !ok {
        +                    queue.Push(neighour)
        +                }
        +            }
        +        }
        +
        +    }
        +}
        +
        +func SearchGraph2(start int) {
        +    queue := structures.NewQueue()
        +    queue.Push(start)
        +    visited := make(map[int]bool)
        +    for queue.Len() > 0 {
        +        node := queue.Pop()
        +        if !visited[node] {
        +            fmt.Printf("%d ", node)
        +            visited[node] = true
        +            neighbors := fetchNeighbours(node)
        +            for _, neighbor := range neighbors {
        +                if !visited[neighbor] {
        +                    queue.Push(neighbor)
        +                }
        +            }
        +        }
        +    }
        +}
        +
        +

        Reference

        + +
        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
        + +
        + +
        +
        +
        + +

        results matching ""

        +
          + +
          +
          + +

          No results matching ""

          + +
          +
          +
          + +
          +
          + +
          + + + + + + + + + + +
          + + +
          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Algorithms/SearchGraph/main.go b/Algorithms/SearchGraph/main.go new file mode 100644 index 000000000..c1651e6cb --- /dev/null +++ b/Algorithms/SearchGraph/main.go @@ -0,0 +1,87 @@ +package searchgraph + +import ( + "LeetcodeGolang/Utility/crud" + "LeetcodeGolang/structures" + "fmt" + "strconv" + + jsoniter "github.com/json-iterator/go" +) + +func fetchNeighbours(node int) []int { + crud := crud.NewCrud("https://hackbear.tv/graph/" + strconv.Itoa(node)) + var result = []int{} + + if got := crud.Get(); got.Error != nil { + // fmt.Printf("got = %v", got) + } else { + var json = jsoniter.ConfigCompatibleWithStandardLibrary + json.Unmarshal([]byte(got.Response), &result) + } + return result +} + +/* + 2 + / \ + / \ + 1 - 3 - 5 - 7 + \ / + \ 6 + \ / + 4 +*/ + +// 1 -> [2, 3, 4] +// 2 -> [1, 5] +// 3 -> [1, 5] +// 4 -> [1, 6] +// 5 -> [2, 3, 7] +// 6 -> [4, 7] +// 7 -> [5, 6] +// print : 1,2,3,4,5,6,7 +// Also this is valid : 1,4,3,2,6,5,7 + +// You will be working on this part +/* +ๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏO(V+E)๏ผŒๅ…ถไธญVๆ˜ฏๅœ–ไธญ็ฏ€้ปž็š„ๆ•ธ้‡๏ผŒEๆ˜ฏๅœ–ไธญ้‚Š็š„ๆ•ธ้‡ +*/ +func SearchGraph(start int) { + queue := structures.NewQueue() + queue.Push(start) + visit := make(map[int][]int) + for queue.Len() > 0 { + node := queue.Pop() + if _, ok := visit[node]; !ok { + fmt.Printf("%d ", node) + neighours := fetchNeighbours(node) + visit[node] = neighours + for _, neighour := range neighours { + if _, ok := visit[neighour]; !ok { + queue.Push(neighour) + } + } + } + + } +} + +func SearchGraph2(start int) { + queue := structures.NewQueue() + queue.Push(start) + visited := make(map[int]bool) + for queue.Len() > 0 { + node := queue.Pop() + if !visited[node] { + fmt.Printf("%d ", node) + visited[node] = true + neighbors := fetchNeighbours(node) + for _, neighbor := range neighbors { + if !visited[neighbor] { + queue.Push(neighbor) + } + } + } + } +} diff --git a/Algorithms/SearchGraph/main_test.go b/Algorithms/SearchGraph/main_test.go new file mode 100644 index 000000000..e993d95f2 --- /dev/null +++ b/Algorithms/SearchGraph/main_test.go @@ -0,0 +1,29 @@ +package searchgraph + +import "testing" + +func TestSearchGraph(t *testing.T) { + SearchGraph(1) +} + +func TestSearchGraph2(t *testing.T) { + SearchGraph2(1) +} +func BenchmarkSearchGraph(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + SearchGraph(1) + } +} + +func BenchmarkSearchGraph2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + SearchGraph2(1) + } +} + +// go test -benchmem -run=none LeetcodeGolang/Algorithms/SearchGraph -bench=. +/* + + */ diff --git a/Algorithms/WeightedEditDistance/index.html b/Algorithms/WeightedEditDistance/index.html new file mode 100644 index 000000000..8c26a3b42 --- /dev/null +++ b/Algorithms/WeightedEditDistance/index.html @@ -0,0 +1,3857 @@ + + + + + + + Weighted Edit Distance ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
          +
          + + + + + + + + +
          + +
          + +
          + + + + + + + + +
          +
          + +
          +
          + +
          + +

          WeightedEditDistance

          WeightedEditDistance 是一個計算帶有權重的編輯距離的函式。編輯距離是衡量兩個字串之間的相似度的指標,表示將一個字串轉換為另一個字串所需的最小操作數量。

          +

          在標準的編輯距離算法中,操作包括插入、刪除和替換字符。每個操作都被認為具有相同的代價。然而,在 WeightedEditDistance 中,每個字符的操作代價可以不同,並由一個權重映射表指定。

          +

          函式 WeightedEditDistance 接受兩個字符串 word1word2,以及一個權重映射表 weights。該映射表將每個字符映射到其相應的權重值,用於計算操作的代價。

          +

          該函式使用動態規劃的方法計算編輯距離。它創建一個二維矩陣 dp,其中 dp[i][j] 表示將 word1[:i] 轉換為 word2[:j] 的最小操作代價。

          +

          算法的核心是遍歷 dp 矩陣並計算每個單元格的值。如果 word1[i-1] 等於 word2[j-1],則表示兩個字符相等,不需要進行操作,所以 dp[i][j] 等於 dp[i-1][j-1]。否則,需要考慮插入、刪除和替換操作的代價,並取其中最小的作為 dp[i][j] 的值。

          +

          最終,函式返回 dp[m][n],其中 mn 分別為 word1word2 的長度,表示將整個字串 word1 轉換為 word2 的最小操作代價。

          +

          使用 WeightedEditDistance 函式,您可以根據字符的權重值計算帶有自定義操作代價的編輯距離,以更好地反映兩個字串之間的相似性。

          +

          題目大意

          +

          weightededitdistance 雖然不是一個特定的LeetCode問題,但它涉及到一個概念:加權編輯距離(Weighted Edit Distance)。

          +

          加權編輯距離是指在兩個字串之間進行編輯操作(插入、刪除、替換)時,每個操作具有不同的成本或權重。該問題要求計算從一個字串轉換到另一個字串的最小總成本或權重。

          +

          解題思路

          +

          解決加權編輯距離問題的常用方法是使用動態規劃(Dynamic Programming)。

          +
            +
          1. 創建一個二維數組dp,其中dp[i][j]表示將字串1的前i個字符轉換為字串2的前j個字符的最小加權編輯距離。

            +
          2. +
          3. 初始化dp矩陣的第一行和第一列,分別表示將空字串轉換為字串1和字串2的成本,根據具體問題設置初始值。

            +
          4. +
          5. 遍歷dp矩陣,計算每個dp[i][j]的值,根據以下三種情況進行選擇:

            +
              +
            • 如果字串1的第i個字符等於字串2的第j個字符,則dp[i][j]等於dp[i-1][j-1],即不需要進行編輯操作,繼承前一個狀態的編輯距離。

              +
            • +
            • 否則,dp[i][j]等於插入操作的成本加上dp[i][j-1],刪除操作的成本加上dp[i-1][j],替換操作的成本加上dp[i-1][j-1],取這三種操作的最小值。

              +
            • +
            +
          6. +
          7. 最終,dp[m][n](其中m和n分別為兩個字串的長度)即為兩個字串的最小加權編輯距離。

            +
          8. +
          + + + + + + + + + + + + + +
          替換 /跳過
          dp[i-1][j-1]
          刪除
          dp[i-1][j]
          插入
          dp[i][j-1]
          dp[i][j]
          +

          時間複雜度: 動態規劃的遍歷過程需要計算和填充dp矩陣的每個元素,因此時間複雜度為O(m*n),其中m和n分別為兩個字串的長度。

          +

          空間複雜度: 需要使用一個二維數組dp來保存中間結果,因此空間複雜度為O(m*n)。

          +

          解答

          +
          package weightededitdistance
          +
          +import "fmt"
          +
          +func WeightedEditDistance(word1, word2 string, weights map[rune]int) int {
          +    m, n := len(word1), len(word2)
          +
          +    // 創建二維矩陣用於保存編輯距離
          +    // dp,其中 dp[i][j] 表示將 word1[:i] 轉換為 word2[:j] 的最小操作代價
          +    dp := make([][]int, m+1)
          +    for i := 0; i 
          +

          相關 0072.Edit-Distance

          +
          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
          + +
          + +
          +
          +
          + +

          results matching ""

          +
            + +
            +
            + +

            No results matching ""

            + +
            +
            +
            + +
            +
            + +
            + + + + + + + + + + + + + + +
            + + +
            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Algorithms/WeightedEditDistance/main.go b/Algorithms/WeightedEditDistance/main.go new file mode 100644 index 000000000..a25bcadcf --- /dev/null +++ b/Algorithms/WeightedEditDistance/main.go @@ -0,0 +1,55 @@ +package weightededitdistance + +import "fmt" + +func WeightedEditDistance(word1, word2 string, weights map[rune]int) int { + m, n := len(word1), len(word2) + + // ๅ‰ตๅปบไบŒ็ถญ็Ÿฉ้™ฃ็”จๆ–ผไฟๅญ˜็ทจ่ผฏ่ท้›ข + // dp๏ผŒๅ…ถไธญ dp[i][j] ่กจ็คบๅฐ‡ word1[:i] ่ฝ‰ๆ›็‚บ word2[:j] ็š„ๆœ€ๅฐๆ“ไฝœไปฃๅƒน + dp := make([][]int, m+1) + for i := 0; i <= m; i++ { + dp[i] = make([]int, n+1) + } + + // ๅˆๅง‹ๅŒ–็ฌฌไธ€ๅˆ—, base case + for i := 1; i <= m; i++ { + dp[i][0] = dp[i-1][0] + weights[rune(word1[i-1])] + } + + // ๅˆๅง‹ๅŒ–็ฌฌไธ€่กŒ + for j := 1; j <= n; j++ { + dp[0][j] = dp[0][j-1] + weights[rune(word2[j-1])] + + } + // fmt.Println(dp) + // ๅกซๅ……็ทจ่ผฏ่ท้›ข็Ÿฉ้™ฃ + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + if word1[i-1] == word2[j-1] { + dp[i][j] = dp[i-1][j-1] + } else { + // ่จˆ็ฎ—ๆ’ๅ…ฅใ€ๅˆช้™คๅ’Œๆ›ฟๆ›ๆ“ไฝœ็š„ไปฃๅƒน + // insert: ็›ดๆŽฅๅœจ word1[i]ไธญๆ’ๅ…ฅไธ€ๅ€‹ๅ’Œword2[j]ไธ€ๆจฃ็š„ๅญ—็ฌฆ, ้‚ฃ้บผword2[j]ๅฐฑ่ขซๅŒน้…ไบ†,ๅพ€ๅ‰j, ็นผ็บŒๅ’Œiๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 + insertCost := dp[i][j-1] + weights[rune(word2[j-1])] + deleteCost := dp[i-1][j] + weights[rune(word1[i-1])] + replaceCost := dp[i-1][j-1] + weights[rune(word1[i-1])] + weights[rune(word2[j-1])] + // ๅ–ๆœ€ๅฐ็š„ไปฃๅƒนไฝœ็‚บ็•ถๅ‰ๆ“ไฝœ็š„็ทจ่ผฏ่ท้›ข + dp[i][j] = min(insertCost, deleteCost, replaceCost) + } + } + } + fmt.Println(dp) + return dp[m][n] +} + +// ่ผ”ๅŠฉๅ‡ฝๅผ๏ผŒ่ฟ”ๅ›žไธ‰ๅ€‹ๆ•ธๅญ—ไธญ็š„ๆœ€ๅฐๅ€ผ +func min(a, b, c int) int { + if a <= b && a <= c { + return a + } else if b <= a && b <= c { + return b + } else { + return c + } +} diff --git a/Algorithms/WeightedEditDistance/main_test.go b/Algorithms/WeightedEditDistance/main_test.go new file mode 100644 index 000000000..8ae394558 --- /dev/null +++ b/Algorithms/WeightedEditDistance/main_test.go @@ -0,0 +1,43 @@ +package weightededitdistance + +import ( + "testing" +) + +func TestWeightedEditDistance(t *testing.T) { + tests := []struct { + word1 string + word2 string + weights map[rune]int + expected int + }{ + {"abc", "", map[rune]int{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}, 6}, + {"abc", "def", map[rune]int{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}, 21}, + {"kitten", "sitting", map[rune]int{'k': 1, 'i': 2, 't': 3, 'e': 4, 'n': 5, 's': 6, 'g': 7}, 20}, + } + + for _, test := range tests { + actual := WeightedEditDistance(test.word1, test.word2, test.weights) + if actual != test.expected { + t.Errorf("WeightedEditDistance(%s, %s, %v) = %d, expected %d", test.word1, test.word2, test.weights, actual, test.expected) + } + } +} + +/* +{"abc", "def", map[rune]int{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}, 21}, +a ่ˆ‡ d ็š„ๆ›ฟๆ›ไปฃๅƒน๏ผš1 + 4 = 5 +b ่ˆ‡ e ็š„ๆ›ฟๆ›ไปฃๅƒน๏ผš2 + 5 = 7 +c ่ˆ‡ f ็š„ๆ›ฟๆ›ไปฃๅƒน๏ผš3 + 6 = 9 +ๅ› ๆญค๏ผŒๆœ€ๅฐๆ“ไฝœไปฃๅƒนๆ˜ฏ 5 + 7 + 9 = 21 + +{"kitten", "sitting", map[rune]int{'k': 1, 'i': 2, 't': 3, 'e': 4, 'n': 5, 's': 6, 'g': 7}, 14}, +k ่ฝฌๆขไธบ s ็š„ๆ›ฟๆขไปฃไปท๏ผš1 + 6 = 7 +i ่ฝฌๆขไธบ i ็š„ๆ›ฟๆขไปฃไปท๏ผš0 +t ่ฝฌๆขไธบ t ็š„ๆ›ฟๆขไปฃไปท๏ผš0 +t ่ฝฌๆขไธบ t ็š„ๆ›ฟๆขไปฃไปท๏ผš0 +e ่ฝฌๆขไธบ i ็š„ๆ›ฟๆขไปฃไปท๏ผš4 + 2 = 6 +n ่ฝฌๆขไธบ n ็š„ๆ›ฟๆขไปฃไปท๏ผš5 + 5 = 10 +ๅ› ๆญค๏ผŒๆœ€ๅฐๆ“ไฝœไปฃไปทๆ˜ฏ 7 + 4 + 6 + 6 + 6 + 10 = 39 + +*/ diff --git a/CHANGELOG.html b/CHANGELOG.html new file mode 100644 index 000000000..6df6e4dc0 --- /dev/null +++ b/CHANGELOG.html @@ -0,0 +1,3802 @@ + + + + + + + CHANGELOG ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
            +
            + + + + + + + + +
            + +
            + +
            + + + + + + + + +
            +
            + +
            +
            + +
            + +

            kk2

            +
            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
            + + +
            + +
            +
            +
            + +

            results matching ""

            +
              + +
              +
              + +

              No results matching ""

              + +
              +
              +
              + +
              +
              + +
              + + + + + + + + + + + + + + +
              + + +
              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CodeSignal/Arcade/01.Intro/01.Add/main.go b/CodeSignal/Arcade/01.Intro/01.Add/main.go new file mode 100644 index 000000000..45b4ed8ee --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/01.Add/main.go @@ -0,0 +1,5 @@ +package add + +func Add(param1 int, param2 int) int { + return param1 + param2 +} diff --git a/CodeSignal/Arcade/01.Intro/01.Add/main_test.go b/CodeSignal/Arcade/01.Intro/01.Add/main_test.go new file mode 100644 index 000000000..157663e5a --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/01.Add/main_test.go @@ -0,0 +1,33 @@ +package add + +import ( + "fmt" + "testing" +) + +func TestAddSingel(t *testing.T) { + ans := Add(2, 2) + if ans != 4 { + t.Errorf("IntMin(2) = %d; want 5", ans) + } +} + +func TestAddTableDriven(t *testing.T) { + var tests = []struct { + a, b int + want int + }{ + {1, 1, 2}, + {2, 2, 4}, + {-3, 3, 0}, + } + for _, tt := range tests { + testname := fmt.Sprintf("%d %d", tt.a, tt.b) + t.Run(testname, func(t *testing.T) { + ans := Add(tt.a, tt.b) + if ans != tt.want { + t.Errorf("got %d, want %d", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Arcade/01.Intro/02centuryFromYear/main.go b/CodeSignal/Arcade/01.Intro/02centuryFromYear/main.go new file mode 100644 index 000000000..1ea01fa20 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/02centuryFromYear/main.go @@ -0,0 +1,10 @@ +package centuryfromyear + +func centuryFromYear(year int) int { + carry := year % 100 + if carry > 0 { + return year/100 + 1 + } else { + return year / 100 + } +} diff --git a/CodeSignal/Arcade/01.Intro/02centuryFromYear/main_test.go b/CodeSignal/Arcade/01.Intro/02centuryFromYear/main_test.go new file mode 100644 index 000000000..f10c53da2 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/02centuryFromYear/main_test.go @@ -0,0 +1,33 @@ +package centuryfromyear + +import ( + "fmt" + "testing" +) + +func TestCenturyFromYearSingel(t *testing.T) { + ans := centuryFromYear(2001) + if ans != 21 { + t.Errorf("centuryFromYear(2001) = %d; want 21", ans) + } +} + +func TestCenturyFromYearTableDriven(t *testing.T) { + var tests = []struct { + a int + want int + }{ + {1, 1}, + {1700, 17}, + {2001, 21}, + } + for _, tt := range tests { + testname := fmt.Sprintf("%d ", tt.a) + t.Run(testname, func(t *testing.T) { + ans := centuryFromYear(tt.a) + if ans != tt.want { + t.Errorf("got %d, want %d", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Arcade/01.Intro/03.checkPalindrome/main.go b/CodeSignal/Arcade/01.Intro/03.checkPalindrome/main.go new file mode 100644 index 000000000..b3dd6795d --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/03.checkPalindrome/main.go @@ -0,0 +1,18 @@ +package checkpalindrome + +func checkPalindrome(inputString string) bool { + strLen := len(inputString) + if strLen < 2 { + return true + } + left, right := 0, strLen-1 + + for left < right { + if inputString[left] != inputString[right] { + return false + } + left++ + right-- + } + return true +} diff --git a/CodeSignal/Arcade/01.Intro/03.checkPalindrome/main_test.go b/CodeSignal/Arcade/01.Intro/03.checkPalindrome/main_test.go new file mode 100644 index 000000000..5f13a327e --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/03.checkPalindrome/main_test.go @@ -0,0 +1,33 @@ +package checkpalindrome + +import ( + "fmt" + "testing" +) + +func TestCheckPalindromeSingel(t *testing.T) { + ans := checkPalindrome("abba") + if ans != true { + t.Errorf("checkPalindrome(abba) = %v; want true", ans) + } +} + +func TestCheckPalindromeTableDriven(t *testing.T) { + var tests = []struct { + a string + want bool + }{ + {"abba", true}, + {"abcba", true}, + {"test", false}, + } + for _, tt := range tests { + testname := fmt.Sprintf("%v ", tt.a) + t.Run(testname, func(t *testing.T) { + ans := checkPalindrome(tt.a) + if ans != tt.want { + t.Errorf("got %v, want %v", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Arcade/01.Intro/04.adjacentElementsProduct/main.go b/CodeSignal/Arcade/01.Intro/04.adjacentElementsProduct/main.go new file mode 100644 index 000000000..cf9a01672 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/04.adjacentElementsProduct/main.go @@ -0,0 +1,12 @@ +package adjacentelementsproduct + +func adjacentElementEproduct(inputArray []int) int { + maxProduct := inputArray[0] * inputArray[1] + for i := 1; i < len(inputArray)-1; i++ { + tmpProduct := inputArray[i] * inputArray[i+1] + if tmpProduct > maxProduct { + maxProduct = tmpProduct + } + } + return maxProduct +} diff --git a/CodeSignal/Arcade/01.Intro/04.adjacentElementsProduct/main_test.go b/CodeSignal/Arcade/01.Intro/04.adjacentElementsProduct/main_test.go new file mode 100644 index 000000000..a09530779 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/04.adjacentElementsProduct/main_test.go @@ -0,0 +1,29 @@ +package adjacentelementsproduct + +import ( + "fmt" + "testing" +) + +func TestAdjacentElementEproduct(t *testing.T) { + var tests = []struct { + input []int + want int + }{ + {[]int{3, 6, -2, -5, 7, 3}, 21}, + {[]int{-1, -2}, 2}, + {[]int{5, 1, 2, 3, 1, 4}, 6}, + {[]int{9, 5, 10, 2, 24, -1, -48}, 50}, + {[]int{5, 6, -4, 2, 3, 2, -23}, 30}, + } + + for _, tt := range tests { + testname := fmt.Sprintf("input: %v", tt.input) + t.Run(testname, func(t *testing.T) { + ans := adjacentElementEproduct(tt.input) + if ans != tt.want { + t.Errorf("got %d, want %d", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Arcade/01.Intro/05.shapeArea/main.go b/CodeSignal/Arcade/01.Intro/05.shapeArea/main.go new file mode 100644 index 000000000..56226d4c1 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/05.shapeArea/main.go @@ -0,0 +1,5 @@ +package shapearea + +func shapeArea(n int) int { + return (n-1)*(n-1) + n*n +} diff --git a/CodeSignal/Arcade/01.Intro/05.shapeArea/main_test.go b/CodeSignal/Arcade/01.Intro/05.shapeArea/main_test.go new file mode 100644 index 000000000..45ae63784 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/05.shapeArea/main_test.go @@ -0,0 +1,33 @@ +package shapearea + +import ( + "fmt" + "testing" +) + +func TestShapeAreaSingel(t *testing.T) { + ans := shapeArea(2) + if ans != 5 { + t.Errorf("IntMin(2) = %d; want 5", ans) + } +} + +func TestShapeAreaTableDriven(t *testing.T) { + var tests = []struct { + a int + want int + }{ + {1, 1}, + {2, 5}, + {3, 13}, + } + for _, tt := range tests { + testname := fmt.Sprintf("%d ", tt.a) + t.Run(testname, func(t *testing.T) { + ans := shapeArea(tt.a) + if ans != tt.want { + t.Errorf("got %d, want %d", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Arcade/01.Intro/06.Make-Array-Consecutive-2/main.go b/CodeSignal/Arcade/01.Intro/06.Make-Array-Consecutive-2/main.go new file mode 100644 index 000000000..69817635e --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/06.Make-Array-Consecutive-2/main.go @@ -0,0 +1,27 @@ +package makearrayconsecutive2 + +import "sort" + +func makeArrayConsecutive2(statues []int) int { + sort.Ints(statues) + max := statues[len(statues)-1] + min := statues[0] + total := (max - min) + 1 + + minAdditional := total - len(statues) + + return minAdditional + + // sort.Ints(statues) + // max:=statues[len(statues)-1] + // min:=statues[0] + // currentIdx,result := 0,0 + // for i:= min; i i { + // result++ + // }else{ + // currentIdx++ + // } + // } + // return result +} diff --git a/CodeSignal/Arcade/01.Intro/06.Make-Array-Consecutive-2/main_test.go b/CodeSignal/Arcade/01.Intro/06.Make-Array-Consecutive-2/main_test.go new file mode 100644 index 000000000..499048766 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/06.Make-Array-Consecutive-2/main_test.go @@ -0,0 +1,33 @@ +package makearrayconsecutive2 + +import ( + "fmt" + "testing" +) + +func TestMakeArrayConsecutive2Singel(t *testing.T) { + ans := makeArrayConsecutive2([]int{6, 2, 3, 8}) + if ans != 3 { + t.Errorf("makeArrayConsecutive2([]int{6, 2, 3, 8}) = %d; want 3", ans) + } +} + +func TestMakeArrayConsecutive2TableDriven(t *testing.T) { + var tests = []struct { + a []int + want int + }{ + {[]int{6, 2, 3, 8}, 3}, + {[]int{0, 3}, 2}, + {[]int{5, 4, 6}, 0}, + } + for _, tt := range tests { + testname := fmt.Sprintf("%d ", tt.a) + t.Run(testname, func(t *testing.T) { + ans := makeArrayConsecutive2(tt.a) + if ans != tt.want { + t.Errorf("got %d, want %d", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Arcade/01.Intro/07.almostIncreasingSequence/main.go b/CodeSignal/Arcade/01.Intro/07.almostIncreasingSequence/main.go new file mode 100644 index 000000000..183834663 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/07.almostIncreasingSequence/main.go @@ -0,0 +1,22 @@ +package almostincreasingsequence + +func almostIncreasingSequence(sequence []int) bool { + removed := false + for i := 1; i < len(sequence); i++ { + if sequence[i] <= sequence[i-1] { + if removed { + return false + } + removed = true + if i == 1 || sequence[i] > sequence[i-2] { + // remove index i-1 + sequence[i-1] = sequence[i] + } else { + // remove index i + sequence[i] = sequence[i-1] + } + } + + } + return true +} diff --git a/CodeSignal/Arcade/01.Intro/07.almostIncreasingSequence/main_test.go b/CodeSignal/Arcade/01.Intro/07.almostIncreasingSequence/main_test.go new file mode 100644 index 000000000..fb8048c2d --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/07.almostIncreasingSequence/main_test.go @@ -0,0 +1,40 @@ +package almostincreasingsequence + +import ( + "fmt" + "testing" +) + +func TestAlmostIncreasingSequenceSingel(t *testing.T) { + ans := almostIncreasingSequence([]int{1, 3, 2, 1}) + if ans != false { + t.Errorf("almostIncreasingSequence([]int{1, 3, 2, 1}) = %v; want false", ans) + } +} + +func TestAlmostIncreasingSequenceTableDriven(t *testing.T) { + var tests = []struct { + a []int + want bool + }{ + {[]int{1, 3, 2, 1}, false}, + {[]int{1, 3, 2}, true}, + {[]int{1, 2, 1, 2}, false}, + {[]int{3, 6, 5, 8, 10, 20, 15}, false}, + {[]int{1, 1, 2, 3, 4, 4}, false}, + {[]int{1, 4, 10, 4, 2}, false}, + {[]int{10, 1, 2, 3, 4, 5}, true}, + {[]int{1, 1, 1, 2, 3}, false}, + {[]int{0, -2, 5, 6}, true}, + {[]int{1, 2, 3, 4, 5, 3, 5, 6}, false}, + } + for _, tt := range tests { + testname := fmt.Sprintf("%d ", tt.a) + t.Run(testname, func(t *testing.T) { + ans := almostIncreasingSequence(tt.a) + if ans != tt.want { + t.Errorf("got %v, want %v", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Arcade/01.Intro/08.matrixElementsSum/main.go b/CodeSignal/Arcade/01.Intro/08.matrixElementsSum/main.go new file mode 100644 index 000000000..cf8a6c9df --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/08.matrixElementsSum/main.go @@ -0,0 +1,15 @@ +package matrixelementssum + +// ๅพžๅทฆไธŠๅพ€ๅทฆไธ‹่ตฐ, ้‡ๅˆฐ0ๅฐฑ็ตๆŸ. ไธ€่ทฏ็”ฑๅทฆ้‚Š็ตฑ่จˆๅˆฐๅณ้‚Š +func matrixElementsSum(matrix [][]int) int { + sum := 0 + for i := 0; i < len(matrix[0]); i++ { + for j := 0; j < len(matrix); j++ { + if matrix[j][i] <= 0 { + break + } + sum += matrix[j][i] + } + } + return sum +} diff --git a/CodeSignal/Arcade/01.Intro/08.matrixElementsSum/main_test.go b/CodeSignal/Arcade/01.Intro/08.matrixElementsSum/main_test.go new file mode 100644 index 000000000..693f3f805 --- /dev/null +++ b/CodeSignal/Arcade/01.Intro/08.matrixElementsSum/main_test.go @@ -0,0 +1,53 @@ +package matrixelementssum + +import ( + "fmt" + "testing" +) + +func TestMatrixElementsSumSingel(t *testing.T) { + ans := matrixElementsSum([][]int{{0, 1, 1, 2}, + {0, 5, 0, 0}, + {2, 0, 3, 3}}) + if ans != 9 { + t.Errorf("matrixElementsSum([][]int{{0, 1, 1, 2},{0, 5, 0, 0},{2, 0, 3, 3}})) = %v; want 9", ans) + } +} + +func TestMatrixElementsSumTableDriven(t *testing.T) { + var tests = []struct { + a [][]int + want int + }{ + {[][]int{{0, 1, 1, 2}, + {0, 5, 0, 0}, + {2, 0, 3, 3}}, 9}, + {[][]int{{1, 1, 1, 0}, + {0, 5, 0, 1}, + {2, 1, 3, 10}}, 9}, + {[][]int{{1, 1, 1}, + {2, 2, 2}, + {3, 3, 3}}, 18}, + {[][]int{{0}}, 0}, + {[][]int{{1, 0, 3}, + {0, 2, 1}, + {1, 2, 0}}, 5}, + {[][]int{{1}, + {5}, + {0}, + {3}}, 6}, + {[][]int{{1, 2, 3, 4, 5}}, 15}, + {[][]int{{2}, + {5}, + {10}}, 17}, + } + for _, tt := range tests { + testname := fmt.Sprintf("%v ", tt.a) + t.Run(testname, func(t *testing.T) { + ans := matrixElementsSum(tt.a) + if ans != tt.want { + t.Errorf("got %d, want %d", ans, tt.want) + } + }) + } +} diff --git a/CodeSignal/Bank-Requests/bankrequests.go b/CodeSignal/Bank-Requests/bankrequests.go new file mode 100644 index 000000000..7b11a82f9 --- /dev/null +++ b/CodeSignal/Bank-Requests/bankrequests.go @@ -0,0 +1,183 @@ +package bankrequests + +import ( + "errors" + "fmt" + "regexp" + "strconv" + "strings" + "sync" +) + +var ( + errInvaldTransfer = errors.New("invalid transfer") + errInvaldWithdraw = errors.New("invalid withdraw") + errInvaldDeposit = errors.New("invalid deposit") + errUnknownAction = errors.New("unknown action") +) + +var requestScheme = [][]string{ + 3: {"action", "from", "amount"}, + 4: {"action", "from", "to", "amount"}, +} + +type BankService interface { + getActionName() string + transfer() error + withdraw() error + deposit() error +} + +type Bank struct { + BankService + action string + requestId int + from int + to int + amount int + balances []int + requestFailed bool + failedRequest []int + + mutex sync.RWMutex +} + +func (bank *Bank) getActionName() string { + return bank.action +} + +func (bank *Bank) transfer() error { + bank.mutex.Lock() + defer bank.mutex.Unlock() + + invalidAmout := bank.balances[bank.from-1] < bank.amount + invalidReceiver := len(bank.balances) < bank.to + if invalidAmout || invalidReceiver { + return errInvaldTransfer + } + bank.balances[bank.from-1] -= bank.amount + bank.balances[bank.to-1] += bank.amount + return nil +} + +func (bank *Bank) withdraw() error { + bank.mutex.Lock() + defer bank.mutex.Unlock() + + if bank.balances[bank.from-1] < bank.amount { + return errInvaldWithdraw + } + bank.balances[bank.from-1] -= bank.amount + return nil +} + +func (bank *Bank) deposit() error { + bank.mutex.Lock() + defer bank.mutex.Unlock() + + invalidAccount := len(bank.balances) < bank.from + if invalidAccount { + return errInvaldDeposit + } + bank.balances[bank.from-1] += bank.amount + return nil +} + +func NewBank() *Bank { + return &Bank{} +} + +// ้Œฏ่ชค่™•็†: ๅ›žๅ‚ณ้Œฏ่ชค็‚บ +// ๅ–ฎไธ€ๅ…ƒ็ด ็‚บ`[- ]`็š„ๆ•ธ็ต„๏ผˆ่ซ‹ๆณจๆ„่ฒ ่™Ÿ๏ผ‰ +func (bank *Bank) failedAction() { + bank.mutex.Lock() + defer bank.mutex.Unlock() + failed := []int{-bank.requestId} + + bank.balances = []int{} + bank.requestFailed = true + bank.failedRequest = failed +} + +func (bank *Bank) Action() { + var requestErr error + action := bank.getActionName() + // fmt.Println("action:", action) + + switch action { + case "transfer": + requestErr = bank.transfer() + case "withdraw": + requestErr = bank.withdraw() + case "deposit": + requestErr = bank.deposit() + default: + requestErr = errUnknownAction + } + if requestErr != nil { + fmt.Println("requestErr:", requestErr) + bank.failedAction() + } +} + +func extractRequestParams(request string) map[string]interface{} { + res := map[string]interface{}{} + reqSlice := strToSlice(request) + fmt.Println("reqSlice:", reqSlice) + + // len is 3: {"action", "from", "amount"}, + // len is 4: {"action", "from", "to", "amount"}, + scheme := requestScheme[len(reqSlice)] + + for i, v := range scheme { + res[v] = reqSlice[i] + } + return res +} + +func strToSlice(str string) []interface{} { + var res []interface{} + erp := strings.Fields(str) + + re, err := regexp.Compile("[0-9]+") + if err != nil { + fmt.Println("Error compiling regex:", err) + return nil + } + + for _, v := range erp { + if isNum := re.MatchString(v); isNum { + if n, _ := strconv.Atoi(v); n != 0 { + res = append(res, n) + } + } else { + res = append(res, v) + } + } + + return res +} + +func bankRequests(requests []string, balances []int) []int { + var res []int + for index, request := range requests { + reqParams := extractRequestParams(request) + bank := NewBank() + bank.requestId = index + 1 + bank.action = reqParams["action"].(string) + bank.amount = reqParams["amount"].(int) + bank.from = reqParams["from"].(int) + if _, ok := reqParams["to"]; ok { + bank.to = reqParams["to"].(int) + } + + bank.balances = balances + bank.Action() + + if bank.requestFailed { + return bank.failedRequest + } + res = bank.balances + } + return res +} diff --git a/CodeSignal/Bank-Requests/bankrequests_test.go b/CodeSignal/Bank-Requests/bankrequests_test.go new file mode 100644 index 000000000..9606f71d1 --- /dev/null +++ b/CodeSignal/Bank-Requests/bankrequests_test.go @@ -0,0 +1,58 @@ +package bankrequests + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []string + arg2 []int + want []int +}{ + { + []string{ + "transfer 1 4 10", + "deposit 3 10", + "withdraw 5 15", + }, + []int{20, 30, 10, 90, 60}, + []int{10, 30, 20, 100, 45}, + }, + { + []string{ + "transfer 1 4 40", + "deposit 3 10", + "withdraw 5 65", + }, + []int{20, 30, 10, 90, 60}, + []int{-1}, + }, + { + []string{ + "withdraw 2 10", + "transfer 5 1 20", + "deposit 5 20", + "transfer 3 4 15", + }, + []int{10, 100, 20, 50, 30}, + []int{30, 90, 5, 65, 30}, + }, + { + []string{ + "deposit 3 400", + "transfer 1 2 30", + "withdraw 4 50", + }, + []int{20, 1000, 500, 40, 90}, + []int{-2}, + }, +} + +func TestBankRequests(t *testing.T) { + for _, tt := range tests { + if got := bankRequests(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/CodeSignal/Bank-Requests/index.html b/CodeSignal/Bank-Requests/index.html new file mode 100644 index 000000000..f368e034b --- /dev/null +++ b/CodeSignal/Bank-Requests/index.html @@ -0,0 +1,4081 @@ + + + + + + + Bank Requests ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
              +
              + + + + + + + + +
              + +
              + +
              + + + + + + + + +
              +
              + +
              +
              + +
              + +

              Bank Requests

              A solution to one of my coding interview questions. Complete solution - written in GoLang

              +
              +

              Task:

              +

              You've been asked to program a bot for a popular bank that will automate the management of incoming requests. There are three types of requests the bank can receive:

              +
                +
              • transfer i j sum: request to transfer sum amount of money from the i-th account to the j-th one
              • +
              • deposit i sum: request to deposit sum amount of money in the i-th account
              • +
              • withdraw i sum: request to withdraw sum amount of money from the i-th account.
              • +
              +

              Your bot should also be able to process invalid requests. There are two types of invalid requests: invalid account number in the requests; deposit / withdrawal of a larger amount of money than is currently available.

              +

              For the given list of accounts and requests, return the state of accounts after all requests have been processed, or an array of a single element [- ] (please note the minus sign), where is the 1-based index of the first invalid request.

              +

              Example for accounts = [10, 100, 20, 50, 30] and requests = ["withdraw 2 10", "transfer 5 1 20", "deposit 5 20", "transfer 3 4 15"], the output should be bankRequests(accounts, requests) = [30, 90, 5, 65, 30].

              +

              accounts = [10, 100, 20, 50, 30] : 代表 ID:1 有10元, ID:2 有100元 ... +"withdraw 2 10" : 從ID:2 提領 10元, 所以100-10 最後得到accounts= [10, 90, 20, 50, 30]

              +

              Here are the states of accounts after each request:

              +
                +
              • "withdraw 2 10": [10, 90, 20, 50, 30]
              • +
              • "transfer 5 1 20": [30, 90, 20, 50, 10]
              • +
              • "deposit 5 20": [30, 90, 20, 50, 30]
              • +
              • "transfer 3 4 15": [30, 90, 5, 65, 30], which is the answer
              • +
              +

              For accounts = [20, 1000, 500, 40, 90] and requests = ["deposit 3 400", "transfer 1 2 30", "withdraw 4 50"], the output should be bankRequests(accounts, requests) = [-2].

              +

              After the first request, accounts becomes equal to [20, 1000, 900, 40, 90], but the second one turns it into [-10, 1030, 900, 40, 90], which is invalid. Thus, the second request is invalid, and the answer is [-2]. Note that the last request is also invalid, but it shouldn't be included in the answer.

              +

              中文意思: +你被要求為一家知名銀行編寫一個機器人,該機器人將自動處理來自客戶的請求。銀行可能會收到三種類型的請求:

              +
                +
              • transfer i j sum:從第i個帳戶轉移sum金額到第j個帳戶的請求
              • +
              • deposit i sum:向第i個帳戶存入sum金額的請求
              • +
              • withdraw i sum:從第i個帳戶提取sum金額的請求。
              • +
              +

              你的機器人還應該能夠處理無效的請求。無效的請求有兩種類型:請求中的帳戶號碼無效;存款/提款金額大於當前可用金額。

              +

              對於給定的帳戶列表和請求,返回處理完所有請求後的帳戶狀態,或單一元素為[- ]的數組(請注意負號),其中 是第一個無效請求的從1開始的索引。

              +

              accounts = [10, 100, 20, 50, 30]requests = ["withdraw 2 10", "transfer 5 1 20", "deposit 5 20", "transfer 3 4 15"] 為例,輸出應為 bankRequests(accounts, requests) = [30, 90, 5, 65, 30]

              +

              accounts = [10, 100, 20, 50, 30] 代表:ID:1 有10元, ID:2 有100元 ... +"withdraw 2 10" 從ID:2 提領 10元,所以100-10 最後得到accounts= [10, 90, 20, 50, 30]

              +

              這是每個請求後帳戶的狀態:

              +
                +
              • "withdraw 2 10": [10, 90, 20, 50, 30]
              • +
              • "transfer 5 1 20": [30, 90, 20, 50, 10]
              • +
              • "deposit 5 20": [30, 90, 20, 50, 30]
              • +
              • "transfer 3 4 15": [30, 90, 5, 65, 30],這是答案
              • +
              +

              對於accounts = [20, 1000, 500, 40, 90]requests = ["deposit 3 400", "transfer 1 2 30", "withdraw 4 50"],輸出應為 bankRequests(accounts, requests) = [-2]

              +

              第一個請求後,帳戶變成 [20, 1000, 900, 40, 90],但第二個請求將其變為 [-10, 1030, 900, 40, 90],這是無效的。因此,第二個請求無效,答案為[-2]。請注意最後一個請求也是無效的,但不應包含在答案中。

              +

              解答

              +
              package bankrequests
              +
              +import (
              +    "errors"
              +    "fmt"
              +    "regexp"
              +    "strconv"
              +    "strings"
              +    "sync"
              +)
              +
              +var (
              +    errInvaldTransfer = errors.New("invalid transfer")
              +    errInvaldWithdraw = errors.New("invalid withdraw")
              +    errInvaldDeposit  = errors.New("invalid deposit")
              +    errUnknownAction  = errors.New("unknown action")
              +)
              +
              +var requestScheme = [][]string{
              +    3: {"action", "from", "amount"},
              +    4: {"action", "from", "to", "amount"},
              +}
              +
              +type BankService interface {
              +    getActionName() string
              +    transfer() error
              +    withdraw() error
              +    deposit() error
              +}
              +
              +type Bank struct {
              +    BankService
              +    action        string
              +    requestId     int
              +    from          int
              +    to            int
              +    amount        int
              +    balances      []int
              +    requestFailed bool
              +    failedRequest []int
              +
              +    mutex sync.RWMutex
              +}
              +
              +func (bank *Bank) getActionName() string {
              +    return bank.action
              +}
              +
              +func (bank *Bank) transfer() error {
              +    bank.mutex.Lock()
              +    defer bank.mutex.Unlock()
              +
              +    invalidAmout := bank.balances[bank.from-1] < bank.amount
              +    invalidReceiver := len(bank.balances) < bank.to
              +    if invalidAmout || invalidReceiver {
              +        return errInvaldTransfer
              +    }
              +    bank.balances[bank.from-1] -= bank.amount
              +    bank.balances[bank.to-1] += bank.amount
              +    return nil
              +}
              +
              +func (bank *Bank) withdraw() error {
              +    bank.mutex.Lock()
              +    defer bank.mutex.Unlock()
              +
              +    if bank.balances[bank.from-1] < bank.amount {
              +        return errInvaldWithdraw
              +    }
              +    bank.balances[bank.from-1] -= bank.amount
              +    return nil
              +}
              +
              +func (bank *Bank) deposit() error {
              +    bank.mutex.Lock()
              +    defer bank.mutex.Unlock()
              +
              +    invalidAccount := len(bank.balances) < bank.from
              +    if invalidAccount {
              +        return errInvaldDeposit
              +    }
              +    bank.balances[bank.from-1] += bank.amount
              +    return nil
              +}
              +
              +func NewBank() *Bank {
              +    return &Bank{}
              +}
              +
              +// 錯誤處理: 回傳錯誤為
              +// 單一元素為`[- ]`的數組(請注意負號)
              +func (bank *Bank) failedAction() {
              +    bank.mutex.Lock()
              +    defer bank.mutex.Unlock()
              +    failed := []int{-bank.requestId}
              +
              +    bank.balances = []int{}
              +    bank.requestFailed = true
              +    bank.failedRequest = failed
              +}
              +
              +func (bank *Bank) Action() {
              +    var requestErr error
              +    action := bank.getActionName()
              +    // fmt.Println("action:", action)
              +
              +    switch action {
              +    case "transfer":
              +        requestErr = bank.transfer()
              +    case "withdraw":
              +        requestErr = bank.withdraw()
              +    case "deposit":
              +        requestErr = bank.deposit()
              +    default:
              +        requestErr = errUnknownAction
              +    }
              +    if requestErr != nil {
              +        fmt.Println("requestErr:", requestErr)
              +        bank.failedAction()
              +    }
              +}
              +
              +func extractRequestParams(request string) map[string]interface{} {
              +    res := map[string]interface{}{}
              +    reqSlice := strToSlice(request)
              +    fmt.Println("reqSlice:", reqSlice)
              +
              +    // len is 3: {"action", "from", "amount"},
              +    // len is 4: {"action", "from", "to", "amount"},
              +    scheme := requestScheme[len(reqSlice)]
              +
              +    for i, v := range scheme {
              +        res[v] = reqSlice[i]
              +    }
              +    return res
              +}
              +
              +func strToSlice(str string) []interface{} {
              +    var res []interface{}
              +    erp := strings.Fields(str)
              +
              +    re, err := regexp.Compile("[0-9]+")
              +    if err != nil {
              +        fmt.Println("Error compiling regex:", err)
              +        return nil
              +    }
              +
              +    for _, v := range erp {
              +        if isNum := re.MatchString(v); isNum {
              +            if n, _ := strconv.Atoi(v); n != 0 {
              +                res = append(res, n)
              +            }
              +        } else {
              +            res = append(res, v)
              +        }
              +    }
              +
              +    return res
              +}
              +
              +func bankRequests(requests []string, balances []int) []int {
              +    var res []int
              +    for index, request := range requests {
              +        reqParams := extractRequestParams(request)
              +        bank := NewBank()
              +        bank.requestId = index + 1
              +        bank.action = reqParams["action"].(string)
              +        bank.amount = reqParams["amount"].(int)
              +        bank.from = reqParams["from"].(int)
              +        if _, ok := reqParams["to"]; ok {
              +            bank.to = reqParams["to"].(int)
              +        }
              +
              +        bank.balances = balances
              +        bank.Action()
              +
              +        if bank.requestFailed {
              +            return bank.failedRequest
              +        }
              +        res = bank.balances
              +    }
              +    return res
              +}
              +
              +

              unit test

              +
              package bankrequests
              +
              +import (
              +    "reflect"
              +    "testing"
              +)
              +
              +var tests = []struct {
              +    arg1 []string
              +    arg2 []int
              +    want []int
              +}{
              +    {
              +        []string{
              +            "transfer 1 4 10",
              +            "deposit 3 10",
              +            "withdraw 5 15",
              +        },
              +        []int{20, 30, 10, 90, 60},
              +        []int{10, 30, 20, 100, 45},
              +    },
              +    {
              +        []string{
              +            "transfer 1 4 40",
              +            "deposit 3 10",
              +            "withdraw 5 65",
              +        },
              +        []int{20, 30, 10, 90, 60},
              +        []int{-1},
              +    },
              +    {
              +        []string{
              +            "withdraw 2 10",
              +            "transfer 5 1 20",
              +            "deposit 5 20",
              +            "transfer 3 4 15",
              +        },
              +        []int{10, 100, 20, 50, 30},
              +        []int{30, 90, 5, 65, 30},
              +    },
              +    {
              +        []string{
              +            "deposit 3 400",
              +            "transfer 1 2 30",
              +            "withdraw 4 50",
              +        },
              +        []int{20, 1000, 500, 40, 90},
              +        []int{-2},
              +    },
              +}
              +
              +func TestBankRequests(t *testing.T) {
              +    for _, tt := range tests {
              +        if got := bankRequests(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) {
              +            t.Errorf("got = %v, want = %v", got, tt.want)
              +        }
              +    }
              +}
              +
              +

              Reference

              + +
              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
              + +
              + +
              +
              +
              + +

              results matching ""

              +
                + +
                +
                + +

                No results matching ""

                + +
                +
                +
                + +
                +
                + +
                + + + + + + +
                + + +
                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CodeSignal/index.html b/CodeSignal/index.html new file mode 100644 index 000000000..abbe12c3e --- /dev/null +++ b/CodeSignal/index.html @@ -0,0 +1,3803 @@ + + + + + + + Code Signal ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                +
                + + + + + + + + +
                + +
                + +
                + + + + + + + + +
                +
                + +
                +
                + +
                + +

                Code Signal

                +

                Reference

                + +
                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                + + +
                + +
                +
                +
                + +

                results matching ""

                +
                  + +
                  +
                  + +

                  No results matching ""

                  + +
                  +
                  +
                  + +
                  +
                  + +
                  + + + + + + + + + + +
                  + + +
                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap.go b/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap.go new file mode 100644 index 000000000..174e6c4e9 --- /dev/null +++ b/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap.go @@ -0,0 +1,38 @@ +package binarygap + +// O(log n) +func Solution(N int) int { + maxLen, curLen := 0, 0 + findOne := false + for N > 0 { + curBit := N & 1 + if curBit == 1 { + curLen = 0 + findOne = true + } else if curBit == 0 && findOne { + curLen++ + } + + if curLen > maxLen { + maxLen = curLen + } + N = N >> 1 + } + return maxLen +} + +// https://wandbox.org/permlink/totZwDAbL1wCgsqt +func evil(x int) int { + if x&(x+1) > 0 { + return evil(x|(x>>1)) + 1 + } else { + return 0 + } +} + +func SolutionRecur(N int) int { + for (N & 1) == 0 { + N = N >> 1 + } + return evil(N) +} diff --git a/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap_test.go b/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap_test.go new file mode 100644 index 000000000..5e94a2e2a --- /dev/null +++ b/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap_test.go @@ -0,0 +1,41 @@ +package binarygap + +import "testing" + +var tests = []struct { + arg1 int + want int +}{ + { + 141, // 1000 1101 + 3, + }, + { + 1041, // 10100 0001 0001 + 5, + }, + { + 32, // 10100 0001 0001 + 0, + }, + { + 2147483647, // 2^31-1: 0111 1111 1111 1111 1111 1111 1111 1111 + 0, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolutionRecur(t *testing.T) { + for _, tt := range tests { + if got := SolutionRecur(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0001.Iterations/Binary-Gap/index.html b/Codility/Lesson/0001.Iterations/Binary-Gap/index.html new file mode 100644 index 000000000..922300282 --- /dev/null +++ b/Codility/Lesson/0001.Iterations/Binary-Gap/index.html @@ -0,0 +1,3852 @@ + + + + + + + Binary Gap ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  +
                  + + + + + + + + +
                  + +
                  + +
                  + + + + + + + + +
                  +
                  + +
                  +
                  + +
                  + +

                  BinaryGap

                  START +Find longest sequence of zeros in binary representation of an integer.

                  +

                  題目

                  +

                  A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N.

                  +

                  For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.

                  +

                  Write a function:

                  +

                  func Solution(N int) int

                  +

                  that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap.

                  +

                  For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps.

                  +

                  Write an efficient algorithm for the following assumptions:

                  +

                  N is an integer within the range [1..2,147,483,647]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                  +

                  題目大意

                  +

                  輸入正整數, 找出此數在二進位,兩個bit值為1中裡面隔著最多0的長度

                  +

                  解題思路

                  +

                  先找出bit 1的位子, 再開始算中間最長的長度 +解題思路通常可以使用位運算來處理二進制數字。我們可以將N轉換為二進制表示,然後使用遍歷或迴圈來找到相鄰1之間的最大距離。可以使用兩個指針來記錄相鄰的1的

                  +

                  時間複雜度: 解題思路中的遍歷或迴圈需要將N轉換為二進制,因此時間複雜度取決於二進制表示的位數。假設N的位數為k,則時間複雜度為O(k)。

                  +

                  空間複雜度: 解題思路中不需要使用額外的數據結構,只需要使用幾個變數來保存位置和計算結果,因此空間複雜度為O(1)。

                  +

                  來源

                  + +

                  解答

                  +

                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap.go

                  +
                  package binarygap
                  +
                  +// O(log n)
                  +func Solution(N int) int {
                  +    maxLen, curLen := 0, 0
                  +    findOne := false
                  +    for N > 0 {
                  +        curBit := N & 1
                  +        if curBit == 1 {
                  +            curLen = 0
                  +            findOne = true
                  +        } else if curBit == 0 && findOne {
                  +            curLen++
                  +        }
                  +
                  +        if curLen > maxLen {
                  +            maxLen = curLen
                  +        }
                  +        N = N >> 1
                  +    }
                  +    return maxLen
                  +}
                  +
                  +// https://wandbox.org/permlink/totZwDAbL1wCgsqt
                  +func evil(x int) int {
                  +    if x&(x+1) > 0 {
                  +        return evil(x|(x>>1)) + 1
                  +    } else {
                  +        return 0
                  +    }
                  +}
                  +
                  +func SolutionRecur(N int) int {
                  +    for (N & 1) == 0 {
                  +        N = N >> 1
                  +    }
                  +    return evil(N)
                  +}
                  +
                  +
                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                  + +
                  + +
                  +
                  +
                  + +

                  results matching ""

                  +
                    + +
                    +
                    + +

                    No results matching ""

                    + +
                    +
                    +
                    + +
                    +
                    + +
                    + + + + + + +
                    + + +
                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation.go b/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation.go new file mode 100644 index 000000000..3d3d94a4b --- /dev/null +++ b/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation.go @@ -0,0 +1,20 @@ +package cyclicrotation + +func Solution(A []int, K int) []int { + if K == 0 || len(A) <= 1 { + return A + } + + K = K % len(A) + return append(A[len(A)-K:], A[:len(A)-K]...) +} + +func Solution2(A []int, K int) []int { + if K == 0 || len(A) <= 1 { + return A + } + if K > len(A) { + K = K % len(A) + } + return append(A[len(A)-K:], A[:len(A)-K]...) +} diff --git a/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation_test.go b/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation_test.go new file mode 100644 index 000000000..02e15ba03 --- /dev/null +++ b/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation_test.go @@ -0,0 +1,60 @@ +package cyclicrotation + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + arg2 int + want []int +}{ + { + []int{3, 8, 9, 7, 6}, + 3, + []int{9, 7, 6, 3, 8}, + }, + { + []int{0, 0, 0}, + 1, + []int{0, 0, 0}, + }, + { + []int{1, 2, 3, 4}, + 4, + []int{1, 2, 3, 4}, + }, + { + []int{-1, 2, 3, 4, 7, 10, -10}, + 8, + []int{-10, -1, 2, 3, 4, 7, 10}, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSolution(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Solution(tests[3].arg1, tests[3].arg2) + } +} +func BenchmarkSolution2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Solution2(tests[3].arg1, tests[3].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Codility/Lesson/0002.Array/CyclicRotation -bench=. +BenchmarkSolution-4 19386909 56.24 ns/op 64 B/op 1 allocs/op +BenchmarkSolution2-4 20282828 54.88 ns/op 64 B/op 1 allocs/op +*/ diff --git a/Codility/Lesson/0002.Array/CyclicRotation/index.html b/Codility/Lesson/0002.Array/CyclicRotation/index.html new file mode 100644 index 000000000..b39f5a30c --- /dev/null +++ b/Codility/Lesson/0002.Array/CyclicRotation/index.html @@ -0,0 +1,3840 @@ + + + + + + + Cyclic Rotation ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                    +
                    + + + + + + + + +
                    + +
                    + +
                    + + + + + + + + +
                    +
                    + +
                    +
                    + +
                    + +

                    CyclicRotation

                    An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place).

                    +

                    The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.

                    +

                    Write a function:

                    +

                    func Solution(A []int, K int) []int

                    +

                    that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

                    +

                    For example, given

                    +
                    A = [3, 8, 9, 7, 6]
                    +K = 3
                    +

                    the function should return [9, 7, 6, 3, 8]. Three rotations were made:

                    +
                    [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
                    +[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
                    +[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
                    +

                    For another example, given

                    +
                    A = [0, 0, 0]
                    +K = 1
                    +

                    the function should return [0, 0, 0]

                    +

                    Given

                    +
                    A = [1, 2, 3, 4]
                    +K = 4
                    +

                    the function should return [1, 2, 3, 4]

                    +

                    Assume that:

                    +

                    N and K are integers within the range [0..100]; +each element of array A is an integer within the range [−1,000..1,000]. +In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment.

                    +

                    Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                    +

                    題目大意

                    +

                    CyclicRotation題目要求將給定的整數陣列按照給定的旋轉步數進行循環右移,並返回旋轉後的陣列。例如,如果陣列是[3, 8, 9, 7, 6]且旋轉步數是3,則右移後的陣列為[9, 7, 6, 3, 8]。

                    +

                    解題思路

                    +

                    解題思路可以使用多種方法。一種常見的方法是使用額外的陣列來存儲旋轉後的結果。另一種方法是通過循環右移的操作,直接在原始陣列上進行元素交換。根據旋轉步數,我們可以將陣列分為兩個部分,並進行相應的元素交換操作。

                    +

                    時間複雜度: 解題思路中的操作需要遍歷整個陣列,因此時間複雜度為O(N),其中N是陣列的長度。 +空間複雜度: 解題思路中使用了額外的陣列或進行原地交換,不需要使用額外的數據結構,因此空間複雜度為O(1)。

                    +

                    來源

                    + +

                    解答

                    +

                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation.go

                    +
                    package cyclicrotation
                    +
                    +func Solution(A []int, K int) []int {
                    +    if K == 0 || len(A) <= 0="" 1="" {="" return="" a="" }="" k="K" %="" len(a)="" append(a[len(a)-k:],="" a[:len(a)-k]...)="" func="" solution2(a="" []int,="" int)="" []int="" if="" ||="" <="1"> len(A) {
                    +        K = K % len(A)
                    +    }
                    +    return append(A[len(A)-K:], A[:len(A)-K]...)
                    +}
                    +
                    +
                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                    + +
                    + +
                    +
                    +
                    + +

                    results matching ""

                    +
                      + +
                      +
                      + +

                      No results matching ""

                      + +
                      +
                      +
                      + +
                      +
                      + +
                      + + + + + + + + + + +
                      + + +
                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray.go b/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray.go new file mode 100644 index 000000000..162134e7c --- /dev/null +++ b/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray.go @@ -0,0 +1,25 @@ +package oddoccurrencesinarray + +func Solution(A []int) int { + intMap := make(map[int]int) + for i := 0; i < len(A); i++ { + intMap[A[i]] += 1 + } + + for k, v := range intMap { + if v%2 != 0 { + return k + } + } + return -1 +} + +// ๆ‰€ๆœ‰็š„ๆ•ดๆ•ธXOR่ตทไพ†, ่‹ฅๆ˜ฏๅ…ฉๅ€‹ๆ•ดๆ•ธ็›ธๅŒXORๅพ—ๅˆฐ0, ๆœ€ๅพŒๅ‰ฉไธ‹ๅŸบๆ•ธๆฌก็š„ๆ•ธๅญ— +// ๅ‰ๆๅช่ƒฝๆœ‰ไธ€ๅ€‹ๅŸบๆ•ธๆ•ธๅญ— +func Solution2(A []int) int { + result := 0 + for i := 0; i < len(A); i++ { + result ^= A[i] + } + return result +} diff --git a/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray_test.go b/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray_test.go new file mode 100644 index 000000000..274066b2c --- /dev/null +++ b/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray_test.go @@ -0,0 +1,51 @@ +package oddoccurrencesinarray + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{9, 3, 9, 3, 9, 7, 9}, + 7, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolution2(t *testing.T) { + for _, tt := range tests { + if got := Solution2(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSolution(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Solution(tests[0].arg1) + } +} +func BenchmarkSolution2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Solution2(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Codility/Lesson/0002.Array/OddOccurrencesInArray -bench=. +BenchmarkSolution-4 5143094 224.6 ns/op 48 B/op 2 allocs/op +BenchmarkSolution2-4 335248345 3.501 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Codility/Lesson/0002.Array/OddOccurrencesInArray/index.html b/Codility/Lesson/0002.Array/OddOccurrencesInArray/index.html new file mode 100644 index 000000000..073632adc --- /dev/null +++ b/Codility/Lesson/0002.Array/OddOccurrencesInArray/index.html @@ -0,0 +1,3857 @@ + + + + + + + Odd Occurrences In Array ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                      +
                      + + + + + + + + +
                      + +
                      + +
                      + + + + + + + + +
                      +
                      + +
                      +
                      + +
                      + +

                      OddOccurrencesInArray

                      +

                      A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

                      +

                      For example, in array A such that:

                      +

                      A[0] = 9 A[1] = 3 A[2] = 9 + A[3] = 3 A[4] = 9 A[5] = 7 + A[6] = 9 +the elements at indexes 0 and 2 have value 9, +the elements at indexes 1 and 3 have value 3, +the elements at indexes 4 and 6 have value 9, +the element at index 5 has value 7 and is unpaired. +Write a function:

                      +

                      func Solution(A []int) int

                      +

                      that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.

                      +

                      For example, given array A such that:

                      +

                      A[0] = 9 A[1] = 3 A[2] = 9 + A[3] = 3 A[4] = 9 A[5] = 7 + A[6] = 9 +the function should return 7, as explained in the example above.

                      +

                      Write an efficient algorithm for the following assumptions:

                      +

                      N is an odd integer within the range [1..1,000,000]; +each element of array A is an integer within the range [1..1,000,000,000]; +all but one of the values in A occur an even number of times. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                      +

                      題目大意

                      +

                      給定一個非空array A,包含有N個整數,找出只出現基數次的整式

                      +

                      解題思路

                      +
                        +
                      1. 方法一: 可以用Map紀錄每個整數出現的次數, 在檢查是否是偶數
                      2. +
                      3. 方法二: 所有的整數XOR起來, 若是兩個整數相同XOR得到0, 最後剩下基數次的數字
                      4. +
                      +

                      來源

                      + +

                      解答

                      +

                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray.go

                      +
                      package oddoccurrencesinarray
                      +
                      +func Solution(A []int) int {
                      +    intMap := make(map[int]int)
                      +    for i := 0; i < len(A); i++ {
                      +        intMap[A[i]] += 1
                      +    }
                      +
                      +    for k, v := range intMap {
                      +        if v%2 != 0 {
                      +            return k
                      +        }
                      +    }
                      +    return -1
                      +}
                      +
                      +// 所有的整數XOR起來, 若是兩個整數相同XOR得到0, 最後剩下基數次的數字
                      +// 前提只能有一個基數數字
                      +func Solution2(A []int) int {
                      +    result := 0
                      +    for i := 0; i < len(A); i++ {
                      +        result ^= A[i]
                      +    }
                      +    return result
                      +}
                      +
                      +
                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                      + + +
                      + +
                      +
                      +
                      + +

                      results matching ""

                      +
                        + +
                        +
                        + +

                        No results matching ""

                        + +
                        +
                        +
                        + +
                        +
                        + +
                        + + + + + + + + + + +
                        + + +
                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp.go b/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp.go new file mode 100644 index 000000000..58461f6fd --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp.go @@ -0,0 +1,13 @@ +package frogjump + +import ( + "math" +) + +func Solution(X int, Y int, D int) int { + if Y < X { + return 0 + } + remainDist := Y - X + return int(math.Ceil(float64(remainDist) / float64(D))) +} diff --git a/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp_test.go b/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp_test.go new file mode 100644 index 000000000..400ac24b0 --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp_test.go @@ -0,0 +1,28 @@ +package frogjump + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 int + arg2 int + arg3 int + want int +}{ + { + 10, 80, 30, 3, + }, + { + 50, 40, 30, 0, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2, tt.arg3); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0003.Time-Complexity/FrogJmp/index.html b/Codility/Lesson/0003.Time-Complexity/FrogJmp/index.html new file mode 100644 index 000000000..26a94a276 --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/FrogJmp/index.html @@ -0,0 +1,3835 @@ + + + + + + + Frog Jmp ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                        +
                        + + + + + + + + +
                        + +
                        + +
                        + + + + + + + + +
                        +
                        + +
                        +
                        + +
                        + +

                        FrogJmp

                        +

                        A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D.

                        +

                        Count the minimal number of jumps that the small frog must perform to reach its target.

                        +

                        Write a function:

                        +

                        func Solution(X int, Y int, D int) int

                        +

                        that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.

                        +

                        For example, given:

                        +

                        X = 10 + Y = 85 + D = 30 +the function should return 3, because the frog will be positioned as follows:

                        +

                        after the first jump, at position 10 + 30 = 40 +after the second jump, at position 10 + 30 + 30 = 70 +after the third jump, at position 10 + 30 + 30 + 30 = 100 +Write an efficient algorithm for the following assumptions:

                        +

                        X, Y and D are integers within the range [1..1,000,000,000]; +X ≤ Y. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                        +

                        題目大意

                        +

                        解題思路

                        +

                        來源

                        + +

                        解答

                        +

                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp.go

                        +
                        package frogjump
                        +
                        +import (
                        +    "math"
                        +)
                        +
                        +func Solution(X int, Y int, D int) int {
                        +    if Y < X {
                        +        return 0
                        +    }
                        +    remainDist := Y - X
                        +    return int(math.Ceil(float64(remainDist) / float64(D)))
                        +}
                        +
                        +
                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                        + + +
                        + +
                        +
                        +
                        + +

                        results matching ""

                        +
                          + +
                          +
                          + +

                          No results matching ""

                          + +
                          +
                          +
                          + +
                          +
                          + +
                          + + + + + + + + + + +
                          + + +
                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem.go b/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem.go new file mode 100644 index 000000000..d410a7c18 --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem.go @@ -0,0 +1,16 @@ +package permmissingelem + +func Solution(A []int) int { + if len(A) < 1 { + return 1 + } + + n := len(A) + 1 + predictSume := (n + 1) * n / 2 + + var sum int + for _, v := range A { + sum += v + } + return predictSume - sum +} diff --git a/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem_test.go b/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem_test.go new file mode 100644 index 000000000..cadf8bc56 --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem_test.go @@ -0,0 +1,21 @@ +package permmissingelem + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{5, 3, 4, 2}, + 1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0003.Time-Complexity/PermMissingElem/index.html b/Codility/Lesson/0003.Time-Complexity/PermMissingElem/index.html new file mode 100644 index 000000000..bbb36412e --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/PermMissingElem/index.html @@ -0,0 +1,3843 @@ + + + + + + + Perm Missing Elem ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                          +
                          + + + + + + + + +
                          + +
                          + +
                          + + + + + + + + +
                          +
                          + +
                          +
                          + +
                          + +

                          PermMissingElem

                          +

                          An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.

                          +

                          Your goal is to find that missing element.

                          +

                          Write a function:

                          +

                          func Solution(A []int) int

                          +

                          that, given an array A, returns the value of the missing element.

                          +

                          For example, given array A such that:

                          +

                          A[0] = 2 + A[1] = 3 + A[2] = 1 + A[3] = 5 +the function should return 4, as it is the missing element.

                          +

                          Write an efficient algorithm for the following assumptions:

                          +

                          N is an integer within the range [0..100,000]; +the elements of A are all distinct; +each element of array A is an integer within the range [1..(N + 1)]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                          +

                          題目大意

                          +

                          解題思路

                          +

                          來源

                          + +

                          解答

                          +

                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem.go

                          +
                          package permmissingelem
                          +
                          +func Solution(A []int) int {
                          +    if len(A) < 1 {
                          +        return 1
                          +    }
                          +
                          +    n := len(A) + 1
                          +    predictSume := (n + 1) * n / 2
                          +
                          +    var sum int
                          +    for _, v := range A {
                          +        sum += v
                          +    }
                          +    return predictSume - sum
                          +}
                          +
                          +
                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                          + + +
                          + +
                          +
                          +
                          + +

                          results matching ""

                          +
                            + +
                            +
                            + +

                            No results matching ""

                            + +
                            +
                            +
                            + +
                            +
                            + +
                            + + + + + + + + + + + + + + +
                            + + +
                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium.go b/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium.go new file mode 100644 index 000000000..fc7c628d2 --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium.go @@ -0,0 +1,29 @@ +package TapeEquilibrium + +import "math" + +func Solution(A []int) int { + + totalSum := 0 + for _, v := range A { + totalSum += v + } + + leftSum := A[0] + rightSum := totalSum - leftSum + result := math.MaxInt32 + for i := 1; i < len(A); i++ { + tmpDiff := int(math.Abs(float64(rightSum) - float64(leftSum))) + if tmpDiff < result { + result = tmpDiff + } + rightSum -= A[i] + leftSum += A[i] + } + + if result == math.MaxInt32 { + result = 0 + } + + return result +} diff --git a/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium_test.go b/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium_test.go new file mode 100644 index 000000000..0eba7bf92 --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium_test.go @@ -0,0 +1,21 @@ +package TapeEquilibrium + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{3, 1, 2, 4, 3}, + 1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/index.html b/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/index.html new file mode 100644 index 000000000..8d23b3b8f --- /dev/null +++ b/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/index.html @@ -0,0 +1,3864 @@ + + + + + + + Tape Equilibrium ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                            +
                            + + + + + + + + +
                            + +
                            + +
                            + + + + + + + + +
                            +
                            + +
                            +
                            + +
                            + +

                            TapeEquilibrium

                            +

                            Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|.

                            +

                            A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.

                            +

                            Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].

                            +

                            The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

                            +

                            In other words, it is the absolute difference between the sum of the first part and the sum of the second part.

                            +

                            For example, consider array A such that:

                            +

                            A[0] = 3 + A[1] = 1 + A[2] = 2 + A[3] = 4 + A[4] = 3 +We can split this tape in four places:

                            +

                            P = 1, difference = |3 − 10| = 7 +P = 2, difference = |4 − 9| = 5 +P = 3, difference = |6 − 7| = 1 +P = 4, difference = |10 − 3| = 7 +Write a function:

                            +

                            func Solution(A []int) int

                            +

                            that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.

                            +

                            For example, given:

                            +

                            A[0] = 3 + A[1] = 1 + A[2] = 2 + A[3] = 4 + A[4] = 3 +the function should return 1, as explained above.

                            +

                            Write an efficient algorithm for the following assumptions:

                            +

                            N is an integer within the range [2..100,000]; +each element of array A is an integer within the range [−1,000..1,000].

                            +

                            Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                            +

                            題目大意

                            +

                            解題思路

                            +

                            來源

                            + +

                            解答

                            +

                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium.go

                            +
                            package TapeEquilibrium
                            +
                            +import "math"
                            +
                            +func Solution(A []int) int {
                            +
                            +    totalSum := 0
                            +    for _, v := range A {
                            +        totalSum += v
                            +    }
                            +
                            +    leftSum := A[0]
                            +    rightSum := totalSum - leftSum
                            +    result := math.MaxInt32
                            +    for i := 1; i < len(A); i++ {
                            +        tmpDiff := int(math.Abs(float64(rightSum) - float64(leftSum)))
                            +        if tmpDiff < result {
                            +            result = tmpDiff
                            +        }
                            +        rightSum -= A[i]
                            +        leftSum += A[i]
                            +    }
                            +
                            +    if result == math.MaxInt32 {
                            +        result = 0
                            +    }
                            +
                            +    return result
                            +}
                            +
                            +
                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                            + + +
                            + +
                            +
                            +
                            + +

                            results matching ""

                            +
                              + +
                              +
                              + +

                              No results matching ""

                              + +
                              +
                              +
                              + +
                              +
                              + +
                              + + + + + + + + + + +
                              + + +
                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne.go b/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne.go new file mode 100644 index 000000000..c27dd59b0 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne.go @@ -0,0 +1,12 @@ +package FrogRiverOne + +func Solution(X int, A []int) int { + intMap := make(map[int]bool) + for i := 0; i < len(A); i++ { + intMap[A[i]] = true + if len(intMap) == X { + return i + } + } + return -1 +} diff --git a/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne_test.go b/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne_test.go new file mode 100644 index 000000000..d7e19e0f5 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne_test.go @@ -0,0 +1,28 @@ +package FrogRiverOne + +import "testing" + +var tests = []struct { + arg1 int + arg2 []int + want int +}{ + { + 5, + []int{1, 3, 1, 4, 2, 3, 5, 4}, + 6, + }, + { + 2, + []int{2, 2, 2, 2, 2}, + -1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/index.html b/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/index.html new file mode 100644 index 000000000..fd1870149 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/index.html @@ -0,0 +1,3851 @@ + + + + + + + Frog River One ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                              +
                              + + + + + + + + +
                              + +
                              + +
                              + + + + + + + + +
                              +
                              + +
                              +
                              + +
                              + +

                              FrogRiverOne

                              +

                              Find the earliest time when a frog can jump to the other side of a river.

                              +

                              A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river.

                              +

                              You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds.

                              +

                              The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river.

                              +

                              For example, you are given integer X = 5 and array A such that:

                              +

                              A[0] = 1 + A[1] = 3 + A[2] = 1 + A[3] = 4 + A[4] = 2 + A[5] = 3 + A[6] = 5 + A[7] = 4 +In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.

                              +

                              Write a function:

                              +

                              func Solution(X int, A []int) int

                              +

                              that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.

                              +

                              If the frog is never able to jump to the other side of the river, the function should return −1.

                              +

                              For example, given X = 5 and array A such that:

                              +

                              A[0] = 1 + A[1] = 3 + A[2] = 1 + A[3] = 4 + A[4] = 2 + A[5] = 3 + A[6] = 5 + A[7] = 4 +the function should return 6, as explained above.

                              +

                              Write an efficient algorithm for the following assumptions:

                              +

                              N and X are integers within the range [1..100,000]; +each element of array A is an integer within the range [1..X]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                              +

                              題目大意

                              +

                              要X步才能到對面, 每一個走過的位子不能重複計算

                              +

                              解題思路

                              +

                              使用map存哪些地方走過

                              +

                              來源

                              + +

                              解答

                              +

                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne.go

                              +
                              package FrogRiverOne
                              +
                              +func Solution(X int, A []int) int {
                              +    intMap := make(map[int]bool)
                              +    for i := 0; i < len(A); i++ {
                              +        intMap[A[i]] = true
                              +        if len(intMap) == X {
                              +            return i
                              +        }
                              +    }
                              +    return -1
                              +}
                              +
                              +
                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                              + + +
                              + +
                              +
                              +
                              + +

                              results matching ""

                              +
                                + +
                                +
                                + +

                                No results matching ""

                                + +
                                +
                                +
                                + +
                                +
                                + +
                                + + + + + + + + + + +
                                + + +
                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters.go b/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters.go new file mode 100644 index 000000000..a701a6147 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters.go @@ -0,0 +1,37 @@ +package MaxCounters + +func Max(x, y int) int { + if x > y { + return x + } + return y +} + +// ๆ™‚้–“ O(N+M) , ็ฉบ้–“ O(N) +func Solution(N int, A []int) []int { + result := make([]int, N) + maxNum := 0 + nowMaxNum := 0 + for i := 0; i < len(A); i++ { + if A[i] > N { + // ๅฆ‚ๆžœA[i] ๅคงๆ–ผ N ๅ‰‡ๅฐ‡่จˆๆ•ธๅ™จไธญๆ‰€ๆœ‰็š„ๆ•ธๆ›ดๆ–ฐ็‚บ่จˆๆ•ธๅ™จ็•ถๅ‰็š„ๆœ€ๅคงๆ•ธๅ€ผ + maxNum = nowMaxNum + } else { + // ๅฆ‚ๆžœA[i] ๅฐๆ–ผ N ๅ‰‡ๅฐ‡่จˆๆ•ธๅ™จไธญๅฐๆ‡‰ไฝ็ฝฎ็š„ๆ•ธ+1, + if result[A[i]-1] < maxNum { + result[A[i]-1] = maxNum + } + result[A[i]-1]++ + + if nowMaxNum < result[A[i]-1] { + nowMaxNum = result[A[i]-1] + } + } + } + for i := 0; i < N; i++ { + if result[i] < maxNum { + result[i] = maxNum + } + } + return result +} diff --git a/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters_test.go b/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters_test.go new file mode 100644 index 000000000..50df55648 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters_test.go @@ -0,0 +1,31 @@ +package MaxCounters + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 int + arg2 []int + want []int +}{ + { + 5, + []int{3, 4, 4, 6, 1, 4, 4}, + []int{3, 2, 2, 4, 2}, + }, + { + 5, + []int{3, 4, 4, 6, 1, 4, 4}, + []int{3, 2, 2, 4, 2}, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0004.Counting-Elements/MaxCounters/index.html b/Codility/Lesson/0004.Counting-Elements/MaxCounters/index.html new file mode 100644 index 000000000..670513535 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/MaxCounters/index.html @@ -0,0 +1,3888 @@ + + + + + + + Max Counters ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                +
                                + + + + + + + + +
                                + +
                                + +
                                + + + + + + + + +
                                +
                                + +
                                +
                                + +
                                + +

                                MaxCounters

                                +

                                Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum.

                                +

                                You are given N counters, initially set to 0, and you have two possible operations on them:

                                +

                                increase(X) − counter X is increased by 1, +max counter − all counters are set to the maximum value of any counter. +A non-empty array A of M integers is given. This array represents consecutive operations:

                                +

                                if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X), +if A[K] = N + 1 then operation K is max counter. +For example, given integer N = 5 and array A such that:

                                +
                                A[0] = 3
                                +A[1] = 4
                                +A[2] = 4
                                +A[3] = 6
                                +A[4] = 1
                                +A[5] = 4
                                +A[6] = 4
                                +

                                the values of the counters after each consecutive operation will be:

                                +
                                (0, 0, 1, 0, 0)
                                +(0, 0, 1, 1, 0)
                                +(0, 0, 1, 2, 0)
                                +(2, 2, 2, 2, 2)
                                +(3, 2, 2, 2, 2)
                                +(3, 2, 2, 3, 2)
                                +(3, 2, 2, 4, 2)
                                +

                                The goal is to calculate the value of every counter after all operations.

                                +

                                Write a function:

                                +

                                func Solution(N int, A []int) []int

                                +

                                that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters.

                                +

                                Result array should be returned as an array of integers.

                                +

                                For example, given:

                                +
                                A[0] = 3
                                +A[1] = 4
                                +A[2] = 4
                                +A[3] = 6
                                +A[4] = 1
                                +A[5] = 4
                                +A[6] = 4
                                +

                                the function should return [3, 2, 2, 4, 2], as explained above.

                                +

                                Write an efficient algorithm for the following assumptions:

                                +

                                N and M are integers within the range [1..100,000]; +each element of array A is an integer within the range [1..N + 1]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                +

                                題目大意

                                +

                                如果A[i] 小於 N 則將計數器中對應位置的數+1, 如果A[i] 大於 N 則將計數器中所有的數更新為計數器當前的最大數值

                                +

                                解題思路

                                +

                                來源

                                +

                                https://app.codility.com/programmers/lessons/4-counting_elements/

                                +

                                解答

                                +

                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters.go

                                +
                                package MaxCounters
                                +
                                +func Max(x, y int) int {
                                +    if x > y {
                                +        return x
                                +    }
                                +    return y
                                +}
                                +
                                +// 時間 O(N+M) , 空間 O(N)
                                +func Solution(N int, A []int) []int {
                                +    result := make([]int, N)
                                +    maxNum := 0
                                +    nowMaxNum := 0
                                +    for i := 0; i < len(A); i++ {
                                +        if A[i] > N {
                                +            // 如果A[i] 大於 N 則將計數器中所有的數更新為計數器當前的最大數值
                                +            maxNum = nowMaxNum
                                +        } else {
                                +            // 如果A[i] 小於 N 則將計數器中對應位置的數+1,
                                +            if result[A[i]-1] < maxNum {
                                +                result[A[i]-1] = maxNum
                                +            }
                                +            result[A[i]-1]++
                                +
                                +            if nowMaxNum < result[A[i]-1] {
                                +                nowMaxNum = result[A[i]-1]
                                +            }
                                +        }
                                +    }
                                +    for i := 0; i < N; i++ {
                                +        if result[i] < maxNum {
                                +            result[i] = maxNum
                                +        }
                                +    }
                                +    return result
                                +}
                                +
                                +
                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                + + +
                                + +
                                +
                                +
                                + +

                                results matching ""

                                +
                                  + +
                                  +
                                  + +

                                  No results matching ""

                                  + +
                                  +
                                  +
                                  + +
                                  +
                                  + +
                                  + + + + + + + + + + + + + + +
                                  + + +
                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger.go b/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger.go new file mode 100644 index 000000000..4d92faaa4 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger.go @@ -0,0 +1,23 @@ +package MissingInteger + +func Solution(A []int) int { + smallNum := 1 + intMap := make(map[int]bool) + + // ๅฐ‡ๅ‡บ็พ็š„ๆ•ธๅญ—ๅกžๅ…ฅmap + for _, v := range A { + if v > 0 && !intMap[v] { + intMap[v] = true + } + } + + for i := 1; i <= len(intMap); i++ { + if !intMap[i] { + // ๆญคๆญฃๆ•ดๆ•ธๆฒ’ๅœจmapๆ‰พๅˆฐ + return i + } + smallNum = i + 1 + } + + return smallNum +} diff --git a/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger_test.go b/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger_test.go new file mode 100644 index 000000000..285b9ae37 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger_test.go @@ -0,0 +1,31 @@ +package MissingInteger + +import ( + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{1, 3, 6, 4, 1, 2}, + 5, + }, + { + []int{1, 2, 3}, + 4, + }, + { + []int{-1, -3}, + 1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0004.Counting-Elements/MissingInteger/index.html b/Codility/Lesson/0004.Counting-Elements/MissingInteger/index.html new file mode 100644 index 000000000..596b75d85 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/MissingInteger/index.html @@ -0,0 +1,3836 @@ + + + + + + + Missing Integer ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                  +
                                  + + + + + + + + +
                                  + +
                                  + +
                                  + + + + + + + + +
                                  +
                                  + +
                                  +
                                  + +
                                  + +

                                  MissingInteger

                                  +

                                  Find the smallest positive integer that does not occur in a given sequence.

                                  +

                                  This is a demo task.

                                  +

                                  Write a function:

                                  +

                                  func Solution(A []int) int

                                  +

                                  that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.

                                  +

                                  For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

                                  +

                                  Given A = [1, 2, 3], the function should return 4.

                                  +

                                  Given A = [−1, −3], the function should return 1.

                                  +

                                  Write an efficient algorithm for the following assumptions:

                                  +

                                  N is an integer within the range [1..100,000]; +each element of array A is an integer within the range [−1,000,000..1,000,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                  +

                                  題目大意

                                  +

                                  找出該array沒出現的最小整數

                                  +

                                  解題思路

                                  +

                                  先講出現的數字記錄起來, 再依序從1開始往後找出最小的整數且沒出現過

                                  +

                                  來源

                                  +

                                  https://app.codility.com/programmers/lessons/4-counting_elements/missing_integer/

                                  +

                                  解答

                                  +

                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger.go

                                  +
                                  package MissingInteger
                                  +
                                  +func Solution(A []int) int {
                                  +    smallNum := 1
                                  +    intMap := make(map[int]bool)
                                  +
                                  +    // 將出現的數字塞入map
                                  +    for _, v := range A {
                                  +        if v > 0 && !intMap[v] {
                                  +            intMap[v] = true
                                  +        }
                                  +    }
                                  +
                                  +    for i := 1; i 
                                  +
                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                  + + +
                                  + +
                                  +
                                  +
                                  + +

                                  results matching ""

                                  +
                                    + +
                                    +
                                    + +

                                    No results matching ""

                                    + +
                                    +
                                    +
                                    + +
                                    +
                                    + +
                                    + + + + + + + + + + + + + + +
                                    + + +
                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck.go b/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck.go new file mode 100644 index 000000000..13673aa86 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck.go @@ -0,0 +1,40 @@ +package PermCheck + +func Solution(A []int) int { + intMap := make(map[int]bool) + + for _, v := range A { + if !intMap[v] { + intMap[v] = true + } else { + // ้‡่ค‡ๅ‡บ็พ + return 0 + } + } + + for i := 1; i <= len(A); i++ { + if !intMap[i] { + return 0 + } + } + return 1 +} + +func Solution2(A []int) int { + intMap := make(map[int]bool) + sum := 0 + for _, v := range A { + if !intMap[v] { + intMap[v] = true + sum += v + } else { + // ้‡่ค‡ๅ‡บ็พ + return 0 + } + } + + if sum == (len(A)+1)*len(A)/2 { + return 1 + } + return 0 +} diff --git a/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck_test.go b/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck_test.go new file mode 100644 index 000000000..51f838a07 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck_test.go @@ -0,0 +1,35 @@ +package PermCheck + +import ( + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{4, 1, 3, 2}, + 1, + }, + { + []int{4, 3, 2}, + 0, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolution2(t *testing.T) { + for _, tt := range tests { + if got := Solution2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0004.Counting-Elements/PermCheck/index.html b/Codility/Lesson/0004.Counting-Elements/PermCheck/index.html new file mode 100644 index 000000000..346eaa308 --- /dev/null +++ b/Codility/Lesson/0004.Counting-Elements/PermCheck/index.html @@ -0,0 +1,3852 @@ + + + + + + + Perm Check ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                    +
                                    + + + + + + + + +
                                    + +
                                    + +
                                    + + + + + + + + +
                                    +
                                    + +
                                    +
                                    + +
                                    + +

                                    PermCheck

                                    +

                                    Check whether array A is a permutation.

                                    +

                                    A non-empty array A consisting of N integers is given.

                                    +

                                    A permutation(排列) is a sequence containing each element from 1 to N once, and only once.

                                    +

                                    For example, array A such that:

                                    +
                                    A[0] = 4
                                    +A[1] = 1
                                    +A[2] = 3
                                    +A[3] = 2
                                    +

                                    is a permutation, but array A such that:

                                    +
                                    A[0] = 4
                                    +A[1] = 1
                                    +A[2] = 3
                                    +

                                    is not a permutation, because value 2 is missing.

                                    +

                                    The goal is to check whether array A is a permutation.

                                    +

                                    Write a function:

                                    +

                                    func Solution(A []int) int

                                    +

                                    that, given an array A, returns 1 if array A is a permutation and 0 if it is not.

                                    +

                                    For example, given array A such that:

                                    +
                                    A[0] = 4
                                    +A[1] = 1
                                    +A[2] = 3
                                    +A[3] = 2
                                    +

                                    the function should return 1.

                                    +

                                    Given array A such that:

                                    +
                                    A[0] = 4
                                    +A[1] = 1
                                    +A[2] = 3
                                    +

                                    the function should return 0.

                                    +

                                    Write an efficient algorithm for the following assumptions:

                                    +

                                    N is an integer within the range [1..100,000]; +each element of array A is an integer within the range [1..1,000,000,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                    +

                                    題目大意

                                    +

                                    如果是連續排列的array 回傳 1 反之回傳1

                                    +

                                    解題思路

                                    +

                                    類似lesson 4的MissingInteger. 先將現有的直寫入到map. 除了檢查是否有重複數字出現外,順便將總和算起來 +最後檢查總時對不對

                                    +

                                    來源

                                    +

                                    https://app.codility.com/programmers/lessons/4-counting_elements/perm_check/

                                    +

                                    解答

                                    +

                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck.go

                                    +
                                    package PermCheck
                                    +
                                    +func Solution(A []int) int {
                                    +    intMap := make(map[int]bool)
                                    +
                                    +    for _, v := range A {
                                    +        if !intMap[v] {
                                    +            intMap[v] = true
                                    +        } else {
                                    +            // 重複出現
                                    +            return 0
                                    +        }
                                    +    }
                                    +
                                    +    for i := 1; i 
                                    +
                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                    + + +
                                    + +
                                    +
                                    +
                                    + +

                                    results matching ""

                                    +
                                      + +
                                      +
                                      + +

                                      No results matching ""

                                      + +
                                      +
                                      +
                                      + +
                                      +
                                      + +
                                      + + + + + + + + + + +
                                      + + +
                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv.go b/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv.go new file mode 100644 index 000000000..bc7e59528 --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv.go @@ -0,0 +1,24 @@ +package CountDiv + +import "math" + +// ๆ™‚้–“: O(n) +func SolutionBurst(A int, B int, K int) int { + result := 0 + for i := A; i <= B; i++ { + if i%K == 0 { + result++ + } + } + + return result +} + +// ๆ™‚้–“:O(1) ็ฉบ้–“: O(1) +func Solution(A int, B int, K int) int { + result := 0 + if A%2 == 0 { + result = 1 + } + return int(math.Floor(float64(B/K))) - int(math.Floor(float64(A/K))) + result +} diff --git a/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv_test.go b/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv_test.go new file mode 100644 index 000000000..e1948c698 --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv_test.go @@ -0,0 +1,32 @@ +package CountDiv + +import ( + "testing" +) + +var tests = []struct { + arg1 int + arg2 int + arg3 int + want int +}{ + { + 6, 11, 2, 3, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2, tt.arg3); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolutionBurst(t *testing.T) { + for _, tt := range tests { + if got := SolutionBurst(tt.arg1, tt.arg2, tt.arg3); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0005.Prefix-Sums/CountDiv/index.html b/Codility/Lesson/0005.Prefix-Sums/CountDiv/index.html new file mode 100644 index 000000000..eef9f111f --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/CountDiv/index.html @@ -0,0 +1,3825 @@ + + + + + + + Count Div ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                      +
                                      + + + + + + + + +
                                      + +
                                      + +
                                      + + + + + + + + +
                                      +
                                      + +
                                      +
                                      + +
                                      + +

                                      CountDiv

                                      +

                                      Compute number of integers divisible by k in range [a..b].

                                      +

                                      Write a function:

                                      +

                                      func Solution(A int, B int, K int) int

                                      +

                                      that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.:

                                      +

                                      { i : A ≤ i ≤ B, i mod K = 0 }

                                      +

                                      For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10.

                                      +

                                      Write an efficient algorithm for the following assumptions:

                                      +

                                      A and B are integers within the range [0..2,000,000,000]; +K is an integer within the range [1..2,000,000,000]; +A ≤ B. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                      +

                                      題目大意

                                      +

                                      A~B之間的數字 mod K 後為0 的數字有幾個

                                      +

                                      解題思路

                                      +

                                      B/K 找出最大的商, A/K 最小的商. 相減取得在此中間之商的數量. 如果A%K==0 需要在+1

                                      +

                                      來源

                                      + +

                                      解答

                                      +

                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv.go

                                      +
                                      package CountDiv
                                      +
                                      +import "math"
                                      +
                                      +// 時間: O(n)
                                      +func SolutionBurst(A int, B int, K int) int {
                                      +    result := 0
                                      +    for i := A; i 
                                      +
                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                      + + +
                                      + +
                                      +
                                      +
                                      + +

                                      results matching ""

                                      +
                                        + +
                                        +
                                        + +

                                        No results matching ""

                                        + +
                                        +
                                        +
                                        + +
                                        +
                                        + +
                                        + + + + + + + + + + +
                                        + + +
                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery.go b/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery.go new file mode 100644 index 000000000..bf2651b19 --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery.go @@ -0,0 +1,110 @@ +package GenomicRangeQuery + +func Solution(S string, P []int, Q []int) []int { + A, C, G, T := prefixSums(S) + result := make([]int, len(P)) + /* + // fmt.Println("A: ", A) + // fmt.Println("C: ", C) + // fmt.Println("G: ", G) + // fmt.Println("T: ", T) + idx 0 1 2 3 4 5 6 7 + S: [C A G C C T A] + A: [0 0 1 1 1 1 1 2] + C: [0 1 1 1 2 3 3 3] + G: [0 0 0 1 1 1 1 1] + T: [0 0 0 0 0 0 1 1] + P: [2 5 0] + Q: [4 5 6] + */ + + for k, _ := range P { + // ๅˆคๆ–ท A[end of slice]-A[Begin of Slice]ๆ˜ฏๅฆๅคงๆ–ผ้›ถ ๅณๅฏๅˆคๆ–ทๆ˜ฏๅฆ A ๅ‡บ็พ้Ž + if A[Q[k]+1]-A[P[k]] > 0 { + result[k] = 1 + } else if C[Q[k]+1]-C[P[k]] > 0 { + result[k] = 2 + } else if G[Q[k]+1]-G[P[k]] > 0 { + result[k] = 3 + } else if T[Q[k]+1]-T[P[k]] > 0 { + result[k] = 4 + } + } + + return result +} + +// ๆ•ธ็ฎ—ๅพž้–‹ๅง‹ๅˆฐๆฏๅ€‹ๅ›บๅฎš็ดขๅผ•็š„A,C,G,Tๅ€‹ๆ•ธ. ้–‹้ ญๆ’ๅ…ฅ0 +func prefixSums(S string) ([]int, []int, []int, []int) { + n := len(S) + A := make([]int, n+1) + C := make([]int, n+1) + G := make([]int, n+1) + T := make([]int, n+1) + + for i := 1; i < n+1; i++ { + s := string(S[i-1]) + A[i] = A[i-1] + C[i] = C[i-1] + G[i] = G[i-1] + T[i] = T[i-1] + + switch s { + case "A": + A[i]++ + case "C": + C[i]++ + case "G": + G[i]++ + case "T": + T[i]++ + } + + } + + return A, C, G, T +} + +func inLoop(arr string, s string) bool { + for _, v := range arr { + if string(v) == s { + return true + } + } + return false +} + +// O(N * M) +func SolutionBurst(S string, P []int, Q []int) []int { + result := make([]int, len(P)) + for i := 0; i < len(P); i++ { + tmp := S[P[i] : Q[i]+1] + if inLoop(tmp, "A") { + result[i] = 1 + } else if inLoop(tmp, "C") { + result[i] = 2 + } else if inLoop(tmp, "G") { + result[i] = 3 + } else if inLoop(tmp, "T") { + result[i] = 4 + } + } + return result +} + +/* +def solutionBySlice(S, P, Q): + result = [] + length = len(P) + for i in range(length): + temp = (S[P[i]:Q[i]+1]) + if "A" in temp: + result.append(1) + elif "C" in temp: + result.append(2) + elif "G" in temp: + result.append(3) + elif "T" in temp: + result.append(4) + return result +*/ diff --git a/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery_test.go b/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery_test.go new file mode 100644 index 000000000..c3820554b --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery_test.go @@ -0,0 +1,36 @@ +package GenomicRangeQuery + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 string + arg2 []int + arg3 []int + want []int +}{ + { + "CAGCCTA", + []int{2, 5, 0}, + []int{4, 5, 6}, + []int{2, 4, 1}, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2, tt.arg3); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolutionBurst(t *testing.T) { + for _, tt := range tests { + if got := SolutionBurst(tt.arg1, tt.arg2, tt.arg3); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/index.html b/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/index.html new file mode 100644 index 000000000..6e62e676a --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/index.html @@ -0,0 +1,3951 @@ + + + + + + + Genomic Range Query ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                        +
                                        + + + + + + + + +
                                        + +
                                        + +
                                        + + + + + + + + +
                                        +
                                        + +
                                        +
                                        + +
                                        + +

                                        GenomicRangeQuery

                                        +

                                        Find the minimal nucleotide(核苷酸) from a range of sequence DNA.

                                        +

                                        A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence?

                                        +

                                        The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 ≤ K < M) requires you to find the minimal impact factor of nucleotides contained in the DNA sequence between positions P[K] and Q[K] (inclusive).

                                        +

                                        For example, consider string S = CAGCCTA and arrays P, Q such that:

                                        +
                                        P[0] = 2    Q[0] = 4
                                        +P[1] = 5    Q[1] = 5
                                        +P[2] = 0    Q[2] = 6
                                        +

                                        The answers to these M = 3 queries are as follows:

                                        +

                                        The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2. +The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4. +The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1. +Write a function:

                                        +

                                        func Solution(S string, P []int, Q []int) []int

                                        +

                                        that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries.

                                        +

                                        Result array should be returned as an array of integers.

                                        +

                                        For example, given the string S = CAGCCTA and arrays P, Q such that:

                                        +
                                        P[0] = 2    Q[0] = 4
                                        +P[1] = 5    Q[1] = 5
                                        +P[2] = 0    Q[2] = 6
                                        +

                                        the function should return the values [2, 4, 1], as explained above.

                                        +

                                        Write an efficient algorithm for the following assumptions:

                                        +

                                        N is an integer within the range [1..100,000]; +M is an integer within the range [1..50,000]; +each element of arrays P, Q is an integer within the range [0..N − 1]; +P[K] ≤ Q[K], where 0 ≤ K < M; +string S consists only of upper-case English letters A, C, G, T. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                        +

                                        題目大意

                                        +

                                        CAGCCTA +A 代表1, C 代表2, G 代表3 ,T 代表4 +K=0: P[0]=2, Q[0]=4 之間的核苷酸 DNA(GCC)因素分別是3和2, 最小的就是2. +K=1: P[1]=5, Q[1]=5 DNA(T),最小的是4. +K=2: P[2]=0, Q[2]=6 DNA(CAGCCTA),最小的是1.

                                        +

                                        解題思路

                                        +

                                        來源

                                        +

                                        https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query/

                                        +

                                        解答

                                        +

                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery.go

                                        +
                                        package GenomicRangeQuery
                                        +
                                        +func Solution(S string, P []int, Q []int) []int {
                                        +    A, C, G, T := prefixSums(S)
                                        +    result := make([]int, len(P))
                                        +    /*
                                        +        // fmt.Println("A: ", A)
                                        +        // fmt.Println("C: ", C)
                                        +        // fmt.Println("G: ", G)
                                        +        // fmt.Println("T: ", T)
                                        +        idx  0 1 2 3 4 5 6 7
                                        +        S:  [C A G C C T A]
                                        +        A:  [0 0 1 1 1 1 1 2]
                                        +        C:  [0 1 1 1 2 3 3 3]
                                        +        G:  [0 0 0 1 1 1 1 1]
                                        +        T:  [0 0 0 0 0 0 1 1]
                                        +        P:  [2 5 0]
                                        +        Q:  [4 5 6]
                                        +    */
                                        +
                                        +    for k, _ := range P {
                                        +        // 判斷 A[end of slice]-A[Begin of Slice]是否大於零 即可判斷是否 A 出現過
                                        +        if A[Q[k]+1]-A[P[k]] > 0 {
                                        +            result[k] = 1
                                        +        } else if C[Q[k]+1]-C[P[k]] > 0 {
                                        +            result[k] = 2
                                        +        } else if G[Q[k]+1]-G[P[k]] > 0 {
                                        +            result[k] = 3
                                        +        } else if T[Q[k]+1]-T[P[k]] > 0 {
                                        +            result[k] = 4
                                        +        }
                                        +    }
                                        +
                                        +    return result
                                        +}
                                        +
                                        +// 數算從開始到每個固定索引的A,C,G,T個數. 開頭插入0
                                        +func prefixSums(S string) ([]int, []int, []int, []int) {
                                        +    n := len(S)
                                        +    A := make([]int, n+1)
                                        +    C := make([]int, n+1)
                                        +    G := make([]int, n+1)
                                        +    T := make([]int, n+1)
                                        +
                                        +    for i := 1; i < n+1; i++ {
                                        +        s := string(S[i-1])
                                        +        A[i] = A[i-1]
                                        +        C[i] = C[i-1]
                                        +        G[i] = G[i-1]
                                        +        T[i] = T[i-1]
                                        +
                                        +        switch s {
                                        +        case "A":
                                        +            A[i]++
                                        +        case "C":
                                        +            C[i]++
                                        +        case "G":
                                        +            G[i]++
                                        +        case "T":
                                        +            T[i]++
                                        +        }
                                        +
                                        +    }
                                        +
                                        +    return A, C, G, T
                                        +}
                                        +
                                        +func inLoop(arr string, s string) bool {
                                        +    for _, v := range arr {
                                        +        if string(v) == s {
                                        +            return true
                                        +        }
                                        +    }
                                        +    return false
                                        +}
                                        +
                                        +// O(N * M)
                                        +func SolutionBurst(S string, P []int, Q []int) []int {
                                        +    result := make([]int, len(P))
                                        +    for i := 0; i < len(P); i++ {
                                        +        tmp := S[P[i] : Q[i]+1]
                                        +        if inLoop(tmp, "A") {
                                        +            result[i] = 1
                                        +        } else if inLoop(tmp, "C") {
                                        +            result[i] = 2
                                        +        } else if inLoop(tmp, "G") {
                                        +            result[i] = 3
                                        +        } else if inLoop(tmp, "T") {
                                        +            result[i] = 4
                                        +        }
                                        +    }
                                        +    return result
                                        +}
                                        +
                                        +/*
                                        +def solutionBySlice(S, P, Q):
                                        +  result = []
                                        +  length = len(P)
                                        +  for i in range(length):
                                        +    temp = (S[P[i]:Q[i]+1])
                                        +    if "A" in temp:
                                        +      result.append(1)
                                        +    elif "C" in temp:
                                        +      result.append(2)
                                        +    elif "G" in temp:
                                        +      result.append(3)
                                        +    elif "T" in temp:
                                        +      result.append(4)
                                        +  return result
                                        +*/
                                        +
                                        +
                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                        + + +
                                        + +
                                        +
                                        +
                                        + +

                                        results matching ""

                                        +
                                          + +
                                          +
                                          + +

                                          No results matching ""

                                          + +
                                          +
                                          +
                                          + +
                                          +
                                          + +
                                          + + + + + + + + + + + + + + +
                                          + + +
                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice.go b/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice.go new file mode 100644 index 000000000..acd928a2d --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice.go @@ -0,0 +1,29 @@ +package MinAvgTwoSlice + +import "math" + +func Solution(A []int) int { + + min := math.MaxFloat64 + minIndex := -1 + for i := 0; i < len(A)-1; i++ { + // 2ๅ€‹ๆ•ธๅนณๅ‡ + if i+1 < len(A) { + tmp := (float64(A[i]) + float64(A[i+1])) / float64(2) + if tmp < min { + min = tmp + minIndex = i + } + } + // 3ๅ€‹ๆ•ธๅนณๅ‡ + if i+2 < len(A) { + tmp := (float64(A[i]) + float64(A[i+1]) + float64(A[i+2])) / float64(3) + if tmp < min { + min = tmp + minIndex = i + } + } + } + + return minIndex +} diff --git a/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice_test.go b/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice_test.go new file mode 100644 index 000000000..e66233cdf --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice_test.go @@ -0,0 +1,31 @@ +package MinAvgTwoSlice + +import ( + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{4, 2, 2, 5, 1, 5, 8}, + 1, + }, + { + []int{1, 3, 6, 4, 1, 2}, + 4, + }, + { + []int{10, 10, -1, 2, 4, -1, 2, -1}, + 5, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/index.html b/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/index.html new file mode 100644 index 000000000..8319441b0 --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/index.html @@ -0,0 +1,3875 @@ + + + + + + + Min Avg Two Slice ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                          +
                                          + + + + + + + + +
                                          + +
                                          + +
                                          + + + + + + + + +
                                          +
                                          + +
                                          +
                                          + +
                                          + +

                                          MinAvgTwoSlice

                                          +

                                          Find the minimal average of any slice containing at least two elements.

                                          +

                                          A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1).

                                          +

                                          For example, array A such that:

                                          +
                                          A[0] = 4
                                          +A[1] = 2
                                          +A[2] = 2
                                          +A[3] = 5
                                          +A[4] = 1
                                          +A[5] = 5
                                          +A[6] = 8
                                          +

                                          contains the following example slices:

                                          +

                                          slice (1, 2), whose average is (2 + 2) / 2 = 2; +slice (3, 4), whose average is (5 + 1) / 2 = 3; +slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5. +The goal is to find the starting position of a slice whose average is minimal.

                                          +

                                          Write a function:

                                          +

                                          func Solution(A []int) int

                                          +

                                          that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.

                                          +

                                          For example, given array A such that:

                                          +
                                          A[0] = 4
                                          +A[1] = 2
                                          +A[2] = 2
                                          +A[3] = 5
                                          +A[4] = 1
                                          +A[5] = 5
                                          +A[6] = 8
                                          +

                                          the function should return 1, as explained above.

                                          +

                                          Write an efficient algorithm for the following assumptions:

                                          +

                                          N is an integer within the range [2..100,000]; +each element of array A is an integer within the range [−10,000..10,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                          +

                                          題目大意

                                          +

                                          找出array兩index中平均值最小 ,並回傳start的 index

                                          +

                                          解題思路

                                          +

                                          最小avg的slice(n,m),m-n+1一定是2或者3,也就是這個最小avg的slice由2個或者3個元素組成 +因為題目中說明 0 因此可以得出2個或者3個元素是最小的組合,比如length=3的數組,你無法一次分出2個slice,length=2的數組也一樣。為什麼要這麼去想呢?因為你要“比較”出最小的avg,怎麼才能"比較"?那就是必須一次至少有2個slice才能相互比較。那麼當N>=4時,我們就能一次最少分出2個slice

                                          +

                                          來源

                                          + +

                                          解答

                                          +

                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice.go

                                          +
                                          package MinAvgTwoSlice
                                          +
                                          +import "math"
                                          +
                                          +func Solution(A []int) int {
                                          +
                                          +    min := math.MaxFloat64
                                          +    minIndex := -1
                                          +    for i := 0; i < len(A)-1; i++ {
                                          +        // 2個數平均
                                          +        if i+1 < len(A) {
                                          +            tmp := (float64(A[i]) + float64(A[i+1])) / float64(2)
                                          +            if tmp < min {
                                          +                min = tmp
                                          +                minIndex = i
                                          +            }
                                          +        }
                                          +        // 3個數平均
                                          +        if i+2 < len(A) {
                                          +            tmp := (float64(A[i]) + float64(A[i+1]) + float64(A[i+2])) / float64(3)
                                          +            if tmp < min {
                                          +                min = tmp
                                          +                minIndex = i
                                          +            }
                                          +        }
                                          +    }
                                          +
                                          +    return minIndex
                                          +}
                                          +
                                          +
                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                          + + +
                                          + +
                                          +
                                          +
                                          + +

                                          results matching ""

                                          +
                                            + +
                                            +
                                            + +

                                            No results matching ""

                                            + +
                                            +
                                            +
                                            + +
                                            +
                                            + +
                                            + + + + + + + + + + + + + + +
                                            + + +
                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars.go b/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars.go new file mode 100644 index 000000000..2c1dfaf30 --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars.go @@ -0,0 +1,16 @@ +package PassingCars + +func Solution(A []int) int { + addBase, result := 0, 0 + for i := 0; i < len(A); i++ { + if A[i] == 0 { + addBase++ + } else { + result += addBase + } + } + if result > 1000000000 { + return -1 + } + return result +} diff --git a/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars_test.go b/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars_test.go new file mode 100644 index 000000000..aec7d3f75 --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars_test.go @@ -0,0 +1,23 @@ +package PassingCars + +import ( + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{0, 1, 0, 1, 1}, + 5, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0005.Prefix-Sums/PassingCars/index.html b/Codility/Lesson/0005.Prefix-Sums/PassingCars/index.html new file mode 100644 index 000000000..ef6c11af7 --- /dev/null +++ b/Codility/Lesson/0005.Prefix-Sums/PassingCars/index.html @@ -0,0 +1,3850 @@ + + + + + + + Passing Cars ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                            +
                                            + + + + + + + + +
                                            + +
                                            + +
                                            + + + + + + + + +
                                            +
                                            + +
                                            +
                                            + +
                                            + +

                                            PassingCars

                                            +

                                            A non-empty array A consisting of N integers is given. The consecutive(連續) elements of array A represent consecutive cars on a road.

                                            +

                                            Array A contains only 0s and/or 1s:

                                            +

                                            0 represents a car traveling east, +1 represents a car traveling west. +The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 ≤ P < Q < N, is passing when P is traveling to the east and Q is traveling to the west.

                                            +

                                            For example, consider array A such that:

                                            +

                                            A[0] = 0 // no.0 car trave to east + A[1] = 1 // no.1 car trave to west + A[2] = 0 // no.2 car trave to east + A[3] = 1 // no.3 car trave to west + A[4] = 1 // no.4 car trave to west +We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4).

                                            +

                                            Write a function:

                                            +

                                            func Solution(A []int) int

                                            +

                                            that, given a non-empty array A of N integers, returns the number of pairs of passing cars.

                                            +

                                            The function should return −1 if the number of pairs of passing cars exceeds 1,000,000,000.

                                            +

                                            For example, given:

                                            +

                                            A[0] = 0 + A[1] = 1 + A[2] = 0 + A[3] = 1 + A[4] = 1 +the function should return 5, as explained above.

                                            +

                                            Write an efficient algorithm for the following assumptions:

                                            +

                                            N is an integer within the range [1..100,000]; +each element of array A is an integer that can have one of the following values: 0, 1.

                                            +

                                            Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                            +

                                            題目大意

                                            +

                                            每台車的車號為A[]的index, 0 代表往東, 1代表往西, 向東的車號需要小於向西的車號. 找出會車的幾種可能性

                                            +

                                            解題思路

                                            +

                                            每一個向東走的車, 都會跟向西的配對. 當遇到向西時組合+1. +所以車號0可以跟所有大於0的向西車配對. 車號2跟所有大於0的向西車配對 +1號車前面只有車號0這選擇. 車號3跟4有車號0跟2這兩個選擇. 所以是1+2*2=5

                                            +

                                            來源

                                            +

                                            https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/

                                            +

                                            解答

                                            +

                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars.go

                                            +
                                            package PassingCars
                                            +
                                            +func Solution(A []int) int {
                                            +    addBase, result := 0, 0
                                            +    for i := 0; i < len(A); i++ {
                                            +        if A[i] == 0 {
                                            +            addBase++
                                            +        } else {
                                            +            result += addBase
                                            +        }
                                            +    }
                                            +    if result > 1000000000 {
                                            +        return -1
                                            +    }
                                            +    return result
                                            +}
                                            +
                                            +
                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                            + + +
                                            + +
                                            +
                                            +
                                            + +

                                            results matching ""

                                            +
                                              + +
                                              +
                                              + +

                                              No results matching ""

                                              + +
                                              +
                                              +
                                              + +
                                              +
                                              + +
                                              + + + + + + + + + + +
                                              + + +
                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0006.Sorting/Distinct/Distinct.go b/Codility/Lesson/0006.Sorting/Distinct/Distinct.go new file mode 100644 index 000000000..2feed16cf --- /dev/null +++ b/Codility/Lesson/0006.Sorting/Distinct/Distinct.go @@ -0,0 +1,29 @@ +package Distinct + +import "sort" + +func Solution(A []int) int { + sort.Ints(A) + if len(A) == 0 { + return 0 + } + result := 1 + for i := 1; i < len(A); i++ { + if A[i] != A[i-1] { + result++ + } + } + return result +} + +func SolutionSet(A []int) int { + set := make(map[int]struct{}) + var void struct{} + + for i := 0; i < len(A); i++ { + if _, ok := set[A[i]]; !ok { + set[A[i]] = void + } + } + return len(set) +} diff --git a/Codility/Lesson/0006.Sorting/Distinct/Distinct_test.go b/Codility/Lesson/0006.Sorting/Distinct/Distinct_test.go new file mode 100644 index 000000000..08f699078 --- /dev/null +++ b/Codility/Lesson/0006.Sorting/Distinct/Distinct_test.go @@ -0,0 +1,55 @@ +package Distinct + +import ( + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{2, 1, 1, 2, 3, 1}, + 3, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolutionSet(t *testing.T) { + for _, tt := range tests { + if got := SolutionSet(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSolution(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Solution(tests[0].arg1) + } +} + +func BenchmarkSolutionSet(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + SolutionSet(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Codility/Lesson/0006.Sorting/Distinct -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Codility/Lesson/0006.Sorting/Distinct +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkSolution-4 15742278 70.30 ns/op 24 B/op 1 allocs/op +BenchmarkSolutionSet-4 14324376 81.14 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Codility/Lesson/0006.Sorting/Distinct/index.html b/Codility/Lesson/0006.Sorting/Distinct/index.html new file mode 100644 index 000000000..3af16005a --- /dev/null +++ b/Codility/Lesson/0006.Sorting/Distinct/index.html @@ -0,0 +1,3849 @@ + + + + + + + Distinct ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                              +
                                              + + + + + + + + +
                                              + +
                                              + +
                                              + + + + + + + + +
                                              +
                                              + +
                                              +
                                              + +
                                              + +

                                              Distinct

                                              +

                                              Compute number of distinct values in an array.

                                              +

                                              Write a function

                                              +

                                              func Solution(A []int) int

                                              +

                                              that, given an array A consisting of N integers, returns the number of distinct values in array A.

                                              +

                                              For example, given array A consisting of six elements such that:

                                              +

                                              A[0] = 2 A[1] = 1 A[2] = 1 + A[3] = 2 A[4] = 3 A[5] = 1 +the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3.

                                              +

                                              Write an efficient algorithm for the following assumptions:

                                              +

                                              N is an integer within the range [0..100,000]; +each element of array A is an integer within the range [−1,000,000..1,000,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                              +

                                              題目大意

                                              +

                                              返回不重複的整數數量

                                              +

                                              解題思路

                                              +
                                                +
                                              1. 方法ㄧ: 先排序, 在檢查當前跟前一個是不是同一個整數. 不是的會結果+1
                                              2. +
                                              3. 方法二: 建立一個set. 最後返回set的長度
                                              4. +
                                              +

                                              來源

                                              +

                                              https://app.codility.com/programmers/lessons/6-sorting/distinct/

                                              +

                                              解答

                                              +

                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/Distinct/Distinct.go

                                              +
                                              package Distinct
                                              +
                                              +import "sort"
                                              +
                                              +func Solution(A []int) int {
                                              +    sort.Ints(A)
                                              +    if len(A) == 0 {
                                              +        return 0
                                              +    }
                                              +    result := 1
                                              +    for i := 1; i < len(A); i++ {
                                              +        if A[i] != A[i-1] {
                                              +            result++
                                              +        }
                                              +    }
                                              +    return result
                                              +}
                                              +
                                              +func SolutionSet(A []int) int {
                                              +    set := make(map[int]struct{})
                                              +    var void struct{}
                                              +
                                              +    for i := 0; i < len(A); i++ {
                                              +        if _, ok := set[A[i]]; !ok {
                                              +            set[A[i]] = void
                                              +        }
                                              +    }
                                              +    return len(set)
                                              +}
                                              +
                                              +
                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                              + + +
                                              + +
                                              +
                                              +
                                              + +

                                              results matching ""

                                              +
                                                + +
                                                +
                                                + +

                                                No results matching ""

                                                + +
                                                +
                                                +
                                                + +
                                                +
                                                + +
                                                + + + + + + + + + + +
                                                + + +
                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree.go b/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree.go new file mode 100644 index 000000000..11b8765ec --- /dev/null +++ b/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree.go @@ -0,0 +1,16 @@ +package MaxProductOfThree + +import "sort" + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func Solution(A []int) int { + sort.Ints(A) + aLen := len(A) + return max(A[0]*A[1]*A[aLen-1], A[aLen-1]*A[aLen-2]*A[aLen-3]) +} diff --git a/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree_test.go b/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree_test.go new file mode 100644 index 000000000..2273822ae --- /dev/null +++ b/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree_test.go @@ -0,0 +1,21 @@ +package MaxProductOfThree + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{-3, 1, 2, -2, 5, 6}, + 60, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0006.Sorting/MaxProductOfThree/index.html b/Codility/Lesson/0006.Sorting/MaxProductOfThree/index.html new file mode 100644 index 000000000..4f12fae2a --- /dev/null +++ b/Codility/Lesson/0006.Sorting/MaxProductOfThree/index.html @@ -0,0 +1,3856 @@ + + + + + + + Max Product Of Three ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                +
                                                + + + + + + + + +
                                                + +
                                                + +
                                                + + + + + + + + +
                                                +
                                                + +
                                                +
                                                + +
                                                + +

                                                MaxProductOfThree

                                                +

                                                Maximize A[P] A[Q] A[R] for any triplet (P, Q, R).

                                                +

                                                A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] A[Q] A[R] (0 ≤ P < Q < R < N).

                                                +

                                                For example, array A such that:

                                                +

                                                A[0] = -3 + A[1] = 1 + A[2] = 2 + A[3] = -2 + A[4] = 5 + A[5] = 6 +contains the following example triplets:

                                                +

                                                (0, 1, 2), product is −3 1 2 = −6 +(1, 2, 4), product is 1 2 5 = 10 +(2, 4, 5), product is 2 5 6 = 60 +Your goal is to find the maximal product of any triplet.

                                                +

                                                Write a function:

                                                +

                                                func Solution(A []int) int

                                                +

                                                that, given a non-empty array A, returns the value of the maximal product of any triplet.

                                                +

                                                For example, given array A such that:

                                                +

                                                A[0] = -3 + A[1] = 1 + A[2] = 2 + A[3] = -2 + A[4] = 5 + A[5] = 6 +the function should return 60, as the product of triplet (2, 4, 5) is maximal.

                                                +

                                                Write an efficient algorithm for the following assumptions:

                                                +

                                                N is an integer within the range [3..100,000]; +each element of array A is an integer within the range [−1,000..1,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                +

                                                題目大意

                                                +

                                                給一整數陣列A,找出陣列中任意三數乘積的最大值

                                                +

                                                解題思路

                                                +

                                                先排序.然後比較 前兩個元素*最後一個元素的乘積最後三個元素的乘積 取最大值

                                                +

                                                來源

                                                +

                                                https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/

                                                +

                                                解答

                                                +

                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree.go

                                                +
                                                package MaxProductOfThree
                                                +
                                                +import "sort"
                                                +
                                                +func max(a, b int) int {
                                                +    if a > b {
                                                +        return a
                                                +    }
                                                +    return b
                                                +}
                                                +
                                                +func Solution(A []int) int {
                                                +    sort.Ints(A)
                                                +    aLen := len(A)
                                                +    return max(A[0]*A[1]*A[aLen-1], A[aLen-1]*A[aLen-2]*A[aLen-3])
                                                +}
                                                +
                                                +
                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                + + +
                                                + +
                                                +
                                                +
                                                + +

                                                results matching ""

                                                +
                                                  + +
                                                  +
                                                  + +

                                                  No results matching ""

                                                  + +
                                                  +
                                                  +
                                                  + +
                                                  +
                                                  + +
                                                  + + + + + + + + + + + + + + +
                                                  + + +
                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections.go b/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections.go new file mode 100644 index 000000000..a29033af5 --- /dev/null +++ b/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections.go @@ -0,0 +1,68 @@ +package NumberOfDiscIntersections + +import "sort" + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func min(a, b int) int { + if a > b { + return b + } + return a +} + +// ๆ™‚้–“่ค‡้›œ O(n^2) +func SolutionDirect(A []int) int { + count := 0 + for indexI, valueI := range A { + tmpArr := A[indexI+1:] + for indexJ, valueJ := range tmpArr { + if valueI+valueJ >= indexJ+indexI+1-indexI { + count++ + } + } + } + + return count +} + +// ๆ™‚้–“่ค‡้›œ O(nlogn) or O(n) +// TODO: ๅพ…็ ”็ฉถ +func Solution(A []int) int { + iLimit := make([]int, len(A)) // ๅทฆ + jLimit := make([]int, len(A)) // ๅณ + result := 0 + + for i := 0; i < len(A); i += 1 { + iLimit[i] = i - A[i] + jLimit[i] = i + A[i] + } + // ้‡ๅฐiLimitไธญ็š„ๆฏๅ€‹ๅ…ƒ็ด ๏ผŒๅˆฉ็”จไบŒๅˆ†ๆŸฅๆ‰พ็ฎ—ๆณ•๏ผŒๆ‰พๅˆฐๅ…ถไธๅฐๆ–ผjLimitไธญๅ…ƒ็ด ็š„ๅ€‹ๆ•ธ + sort.Ints(iLimit) + sort.Ints(jLimit) + for idx, _ := range iLimit { + end := jLimit[idx] + + // Binary search for index of element of the rightmost value less than to the interval-end + count := sort.Search(len(iLimit), func(i int) bool { + return iLimit[i] > end + }) + + // ๅ› ็‚บi=jๆ™‚๏ผŒA[i]+i ่‚ฏๅฎšไธๅฐๆ–ผj-A[j],ไนŸๅฐฑๆ˜ฏ่ชชๅคš็ฎ—ไบ†ไธ€ๅ€‹๏ผŒๅ› ๆญค่ฆๆธ›ๅŽป1ใ€‚ + // ๆธ›ๅŽปidxๆ˜ฏๅ› ็‚บๅœ“็›คAๅ’Œๅœ“็›คB็›ธไบค๏ผŒๆฌกๆ•ธๅŠ ไธŠ1ไบ†๏ผŒๅœ“็›คBๅ’Œๅœ“็›คA็›ธไบคๅฐฑไธ็”จๅ†ๅŠ 1ไบ†ใ€‚ + count = count - idx - 1 + result += count + + if result > 10000000 { + return -1 + } + + } + + return result +} diff --git a/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections_test.go b/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections_test.go new file mode 100644 index 000000000..a1b821b6c --- /dev/null +++ b/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections_test.go @@ -0,0 +1,29 @@ +package NumberOfDiscIntersections + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{1, 5, 2, 1, 4, 0}, + 11, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolutionDirect(t *testing.T) { + for _, tt := range tests { + if got := SolutionDirect(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/index.html b/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/index.html new file mode 100644 index 000000000..46c65eb8c --- /dev/null +++ b/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/index.html @@ -0,0 +1,3918 @@ + + + + + + + Number Of Disc Intersections ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                  +
                                                  + + + + + + + + +
                                                  + +
                                                  + +
                                                  + + + + + + + + +
                                                  +
                                                  + +
                                                  +
                                                  + +
                                                  + +

                                                  NumberOfDiscIntersections

                                                  +

                                                  Compute the number of intersections(相交) in a sequence of discs(圓盤).

                                                  +

                                                  We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses(半徑) of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J].

                                                  +

                                                  We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders).

                                                  +

                                                  The figure below shows discs drawn for N = 6 and A as follows:

                                                  +

                                                  A[0] = 1 + A[1] = 5 + A[2] = 2 + A[3] = 1 + A[4] = 4 + A[5] = 0

                                                  +

                                                  number_of_disc_intersections

                                                  +

                                                  There are eleven (unordered) pairs of discs that intersect, namely:

                                                  +
                                                    +
                                                  • discs 1 and 4 intersect, and both intersect with all the other discs;
                                                  • +
                                                  • disc 2 also intersects with discs 0 and 3. +Write a function:
                                                  • +
                                                  +

                                                  func Solution(A []int) int

                                                  +

                                                  that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.

                                                  +

                                                  Given array A shown above, the function should return 11, as explained above.

                                                  +

                                                  Write an efficient algorithm for the following assumptions:

                                                  +

                                                  N is an integer within the range [0..100,000]; +each element of array A is an integer within the range [0..2,147,483,647]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                  +

                                                  題目大意

                                                  +

                                                  A[0] = 1, 代表在(0,0)的位置上有一個半徑為1的圓. 找出圓相交的個數

                                                  +

                                                  解題思路

                                                  +
                                                    +
                                                  • 方法一: 對於第i,j個圓來說,如果兩個原要相交的話 +
                                                  • +
                                                  +

                                                  參考SolutionDirect. 時間複雜度為O(n^2)

                                                  +
                                                    +
                                                  • 方法二 +也就是將原來的二維的線段列表變為2個一維的列表 +首先遍歷數組A得到A[i]+i組成的數組i_limit,以及j-A[j]組成的數組j_limit。然後再遍歷數組i_limit中的元素S,利用二分查找算法得到數組j_limit中不大於S的元素個數。前一個操作時間複雜度是O(N),二分查找算法時間複雜度是O(LogN),因此最終的時間複雜度為O(N*logN)。參考Solution。 +
                                                  • +
                                                  +

                                                  來源

                                                  + +

                                                  解答

                                                  +

                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections.go

                                                  +
                                                  package NumberOfDiscIntersections
                                                  +
                                                  +import "sort"
                                                  +
                                                  +func max(a, b int) int {
                                                  +    if a > b {
                                                  +        return a
                                                  +    }
                                                  +    return b
                                                  +}
                                                  +
                                                  +func min(a, b int) int {
                                                  +    if a > b {
                                                  +        return b
                                                  +    }
                                                  +    return a
                                                  +}
                                                  +
                                                  +// 時間複雜 O(n^2)
                                                  +func SolutionDirect(A []int) int {
                                                  +    count := 0
                                                  +    for indexI, valueI := range A {
                                                  +        tmpArr := A[indexI+1:]
                                                  +        for indexJ, valueJ := range tmpArr {
                                                  +            if valueI+valueJ >= indexJ+indexI+1-indexI {
                                                  +                count++
                                                  +            }
                                                  +        }
                                                  +    }
                                                  +
                                                  +    return count
                                                  +}
                                                  +
                                                  +// 時間複雜 O(nlogn) or O(n)
                                                  +// TODO: 待研究
                                                  +func Solution(A []int) int {
                                                  +    iLimit := make([]int, len(A)) // 左
                                                  +    jLimit := make([]int, len(A)) // 右
                                                  +    result := 0
                                                  +
                                                  +    for i := 0; i < len(A); i += 1 {
                                                  +        iLimit[i] = i - A[i]
                                                  +        jLimit[i] = i + A[i]
                                                  +    }
                                                  +    // 針對iLimit中的每個元素,利用二分查找算法,找到其不小於jLimit中元素的個數
                                                  +    sort.Ints(iLimit)
                                                  +    sort.Ints(jLimit)
                                                  +    for idx, _ := range iLimit {
                                                  +        end := jLimit[idx]
                                                  +
                                                  +        // Binary search for index of element of the rightmost value less than to the interval-end
                                                  +        count := sort.Search(len(iLimit), func(i int) bool {
                                                  +            return iLimit[i] > end
                                                  +        })
                                                  +
                                                  +        // 因為i=j時,A[i]+i 肯定不小於j-A[j],也就是說多算了一個,因此要減去1。
                                                  +        // 減去idx是因為圓盤A和圓盤B相交,次數加上1了,圓盤B和圓盤A相交就不用再加1了。
                                                  +        count = count - idx - 1
                                                  +        result += count
                                                  +
                                                  +        if result > 10000000 {
                                                  +            return -1
                                                  +        }
                                                  +
                                                  +    }
                                                  +
                                                  +    return result
                                                  +}
                                                  +
                                                  +
                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                  + + +
                                                  + +
                                                  +
                                                  +
                                                  + +

                                                  results matching ""

                                                  +
                                                    + +
                                                    +
                                                    + +

                                                    No results matching ""

                                                    + +
                                                    +
                                                    +
                                                    + +
                                                    +
                                                    + +
                                                    + + + + + + + + + + + + + + +
                                                    + + +
                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0006.Sorting/Triangle/Triangle.go b/Codility/Lesson/0006.Sorting/Triangle/Triangle.go new file mode 100644 index 000000000..14d34dc41 --- /dev/null +++ b/Codility/Lesson/0006.Sorting/Triangle/Triangle.go @@ -0,0 +1,16 @@ +package Triangle + +import "sort" + +func Solution(A []int) int { + if len(A) < 3 { + return 0 + } + sort.Ints(A) + for i := 0; i < len(A)-2; i++ { + if A[i+2] < A[i+1]+A[i] { + return 1 + } + } + return 0 +} diff --git a/Codility/Lesson/0006.Sorting/Triangle/Triangle_test.go b/Codility/Lesson/0006.Sorting/Triangle/Triangle_test.go new file mode 100644 index 000000000..df8c7916d --- /dev/null +++ b/Codility/Lesson/0006.Sorting/Triangle/Triangle_test.go @@ -0,0 +1,21 @@ +package Triangle + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{10, 2, 5, 1, 8, 20}, + 1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0006.Sorting/Triangle/index.html b/Codility/Lesson/0006.Sorting/Triangle/index.html new file mode 100644 index 000000000..fc9856352 --- /dev/null +++ b/Codility/Lesson/0006.Sorting/Triangle/index.html @@ -0,0 +1,3844 @@ + + + + + + + Triangle ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                    +
                                                    + + + + + + + + +
                                                    + +
                                                    + +
                                                    + + + + + + + + +
                                                    +
                                                    + +
                                                    +
                                                    + +
                                                    + +

                                                    Triangle

                                                    +

                                                    Determine whether a triangle can be built from a given set of edges.

                                                    +

                                                    An array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 ≤ P < Q < R < N and:

                                                    +

                                                    A[P] + A[Q] > A[R], +A[Q] + A[R] > A[P], +A[R] + A[P] > A[Q]. +For example, consider array A such that:

                                                    +

                                                    A[0] = 10 A[1] = 2 A[2] = 5 + A[3] = 1 A[4] = 8 A[5] = 20 +Triplet (0, 2, 4) is triangular.

                                                    +

                                                    Write a function:

                                                    +

                                                    func Solution(A []int) int

                                                    +

                                                    that, given an array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise.

                                                    +

                                                    For example, given array A such that:

                                                    +

                                                    A[0] = 10 A[1] = 2 A[2] = 5 + A[3] = 1 A[4] = 8 A[5] = 20 +the function should return 1, as explained above. Given array A such that:

                                                    +

                                                    A[0] = 10 A[1] = 50 A[2] = 5 + A[3] = 1 +the function should return 0.

                                                    +

                                                    Write an efficient algorithm for the following assumptions:

                                                    +

                                                    N is an integer within the range [0..100,000]; +each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].

                                                    +

                                                    Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                    +

                                                    題目大意

                                                    +

                                                    如果該array存在一個三角形的三元組,則返回1, 否則返回0

                                                    +

                                                    解題思路

                                                    +

                                                    從大到小排序, 如果前面的值小於後面兩數和, 則可以組成三角形. 三數皆不能為0或負數

                                                    +

                                                    來源

                                                    +

                                                    https://app.codility.com/programmers/lessons/6-sorting/triangle/

                                                    +

                                                    解答

                                                    +

                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/Triangle/Triangle.go

                                                    +
                                                    package Triangle
                                                    +
                                                    +import "sort"
                                                    +
                                                    +func Solution(A []int) int {
                                                    +    if len(A) < 3 {
                                                    +        return 0
                                                    +    }
                                                    +    sort.Ints(A)
                                                    +    for i := 0; i < len(A)-2; i++ {
                                                    +        if A[i+2] < A[i+1]+A[i] {
                                                    +            return 1
                                                    +        }
                                                    +    }
                                                    +    return 0
                                                    +}
                                                    +
                                                    +
                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                    + + +
                                                    + +
                                                    +
                                                    +
                                                    + +

                                                    results matching ""

                                                    +
                                                      + +
                                                      +
                                                      + +

                                                      No results matching ""

                                                      + +
                                                      +
                                                      +
                                                      + +
                                                      +
                                                      + +
                                                      + + + + + + + + + + +
                                                      + + +
                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets.go b/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets.go new file mode 100644 index 000000000..49841a787 --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets.go @@ -0,0 +1,45 @@ +package Brackets + +import ( + "LeetcodeGolang/Utility/structures" +) + +func Solution(S string) int { + if len(S) == 0 { + return 1 + } + if len(S)%2 != 0 { + return 0 + } + + BracketMap := map[string]string{ + ")": "(", + "]": "[", + "}": "{", + } + + stack := structures.NewArrayStack() + for _, v := range S { + val := string(v) + if val == "(" || val == "[" || val == "{" { + stack.Push(val) + } else if val == ")" || val == "]" || val == "}" { + if stack.IsEmpty() { + return 0 + } + + topVal := stack.Top() + if topVal == BracketMap[val] { + stack.Pop() + } else { + // ๆ‰พไธๅˆฐๅฏ้…ๅฐ็š„ๆ‹ฌ่™Ÿ + return 0 + } + } + } + if stack.IsEmpty() { + return 1 + } else { + return 0 + } +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets_test.go b/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets_test.go new file mode 100644 index 000000000..1d642286e --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets_test.go @@ -0,0 +1,33 @@ +package Brackets + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "{[()()]}", + 1, + }, + { + "([)()]", + 0, + }, + { + ")(", + 0, + }, + { + "", + 1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Brackets/index.html b/Codility/Lesson/0007.Stacks-and-Queues/Brackets/index.html new file mode 100644 index 000000000..f1416ce2d --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Brackets/index.html @@ -0,0 +1,3864 @@ + + + + + + + Brackets ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                      +
                                                      + + + + + + + + +
                                                      + +
                                                      + +
                                                      + + + + + + + + +
                                                      +
                                                      + +
                                                      +
                                                      + +
                                                      + +

                                                      Brackets

                                                      +

                                                      Determine whether a given string of parentheses (multiple types) is properly nested.

                                                      +

                                                      A string S consisting of N characters is considered to be properly nested if any of the following conditions is true:

                                                      +

                                                      S is empty; +S has the form "(U)" or "[U]" or "{U}" where U is a properly nested string; +S has the form "VW" where V and W are properly nested strings. +For example, the string "{[()()]}" is properly nested but "([)()]" is not.

                                                      +

                                                      Write a function:

                                                      +

                                                      func Solution(S string) int

                                                      +

                                                      that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise.

                                                      +

                                                      For example, given S = "{[()()]}", the function should return 1 and given S = "([)()]", the function should return 0, as explained above.

                                                      +

                                                      Write an efficient algorithm for the following assumptions:

                                                      +

                                                      N is an integer within the range [0..200,000]; +string S consists only of the following characters: "(", "{", "[", "]", "}" and/or ")". +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                      +

                                                      題目大意

                                                      +

                                                      括號配對, 可配對回傳1 反之回傳0.

                                                      +

                                                      解題思路

                                                      +

                                                      將左括號都放入stack. 遇到右括號時將stack pop出來並檢查pop出來的左括號是否跟右括號配對.

                                                      +

                                                      來源

                                                      +

                                                      https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/

                                                      +

                                                      解答

                                                      +

                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets.go

                                                      +
                                                      package Brackets
                                                      +
                                                      +import (
                                                      +    "LeetcodeGolang/Utility/structures"
                                                      +)
                                                      +
                                                      +func Solution(S string) int {
                                                      +    if len(S) == 0 {
                                                      +        return 1
                                                      +    }
                                                      +    if len(S)%2 != 0 {
                                                      +        return 0
                                                      +    }
                                                      +
                                                      +    BracketMap := map[string]string{
                                                      +        ")": "(",
                                                      +        "]": "[",
                                                      +        "}": "{",
                                                      +    }
                                                      +
                                                      +    stack := structures.NewArrayStack()
                                                      +    for _, v := range S {
                                                      +        val := string(v)
                                                      +        if val == "(" || val == "[" || val == "{" {
                                                      +            stack.Push(val)
                                                      +        } else if val == ")" || val == "]" || val == "}" {
                                                      +            if stack.IsEmpty() {
                                                      +                return 0
                                                      +            }
                                                      +
                                                      +            topVal := stack.Top()
                                                      +            if topVal == BracketMap[val] {
                                                      +                stack.Pop()
                                                      +            } else {
                                                      +                // 找不到可配對的括號
                                                      +                return 0
                                                      +            }
                                                      +        }
                                                      +    }
                                                      +    if stack.IsEmpty() {
                                                      +        return 1
                                                      +    } else {
                                                      +        return 0
                                                      +    }
                                                      +}
                                                      +
                                                      +
                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                      + + +
                                                      + +
                                                      +
                                                      +
                                                      + +

                                                      results matching ""

                                                      +
                                                        + +
                                                        +
                                                        + +

                                                        No results matching ""

                                                        + +
                                                        +
                                                        +
                                                        + +
                                                        +
                                                        + +
                                                        + + + + + + + + + + +
                                                        + + +
                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish.go b/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish.go new file mode 100644 index 000000000..6dfb599ce --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish.go @@ -0,0 +1,27 @@ +package Fish + +import "LeetcodeGolang/Utility/structures" + +func Solution(A []int, B []int) int { + stack := structures.NewArrayStack() + aliveFish := 0 + for idx, val := range B { + if val == 1 { + stack.Push(A[idx]) + } else { + // ็นผ็บŒๅพ€ไธ‹ๆธธ + for !stack.IsEmpty() { + if stack.Top().(int) < A[idx] { + // stack็š„้ญšๆฏ”้‡ๅˆฐ็š„้ญš้‚„ๅฐ, stack่ขซๅƒๆŽ‰ + stack.Pop() + } else { + break + } + } + if stack.IsEmpty() { + aliveFish++ + } + } + } + return aliveFish + stack.Size() +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish_test.go b/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish_test.go new file mode 100644 index 000000000..334722621 --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish_test.go @@ -0,0 +1,23 @@ +package Fish + +import "testing" + +var tests = []struct { + arg1 []int + arg2 []int + want int +}{ + { + []int{4, 3, 2, 1, 5}, + []int{0, 1, 0, 0, 0}, + 2, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Fish/index.html b/Codility/Lesson/0007.Stacks-and-Queues/Fish/index.html new file mode 100644 index 000000000..3e7871df8 --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Fish/index.html @@ -0,0 +1,3868 @@ + + + + + + + Fish ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                        +
                                                        + + + + + + + + +
                                                        + +
                                                        + +
                                                        + + + + + + + + +
                                                        +
                                                        + +
                                                        +
                                                        + +
                                                        + +

                                                        Fish

                                                        +

                                                        N voracious fish are moving along a river. Calculate how many fish are alive.

                                                        +

                                                        You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river.

                                                        +

                                                        The fish are numbered from 0 to N − 1. If P and Q are two fish and P < Q, then fish P is initially upstream of fish Q. Initially, each fish has a unique position.

                                                        +

                                                        Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where:

                                                        +

                                                        0 represents a fish flowing upstream, +1 represents a fish flowing downstream. +If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive − the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P < Q, B[P] = 1 and B[Q] = 0, and there are no living fish between them. After they meet:

                                                        +

                                                        If A[P] > A[Q] then P eats Q, and P will still be flowing downstream, +If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. +We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive.

                                                        +

                                                        For example, consider arrays A and B such that:

                                                        +

                                                        A[0] = 4 B[0] = 0 + A[1] = 3 B[1] = 1 + A[2] = 2 B[2] = 0 + A[3] = 1 B[3] = 0 + A[4] = 5 B[4] = 0 +Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive.

                                                        +

                                                        Write a function:

                                                        +

                                                        func Solution(A []int, B []int) int

                                                        +

                                                        that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive.

                                                        +

                                                        For example, given the arrays shown above, the function should return 2, as explained above.

                                                        +

                                                        Write an efficient algorithm for the following assumptions:

                                                        +

                                                        N is an integer within the range [1..100,000]; +each element of array A is an integer within the range [0..1,000,000,000]; +each element of array B is an integer that can have one of the following values: 0, 1; +the elements of A are all distinct.

                                                        +

                                                        Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                        +

                                                        題目大意

                                                        +

                                                        最開始每個魚都有特定的起始位置 +A: 活魚的大小, B: 魚游的方向. 如果於相遇的話大魚會吃掉小魚. +返回剩下魚的數量

                                                        +

                                                        解題思路

                                                        +

                                                        從 B 開始找, 當值為1 存入stack. 代表向下游的魚. 來進行把活魚吃掉. 如果把列表的活魚都吃掉. 則結果+1 +如果值為0且stack為空, 代表沒遇到下游的魚所以活魚++

                                                        +

                                                        來源

                                                        +

                                                        https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/

                                                        +

                                                        解答

                                                        +

                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish.go

                                                        +
                                                        package Fish
                                                        +
                                                        +import "LeetcodeGolang/Utility/structures"
                                                        +
                                                        +func Solution(A []int, B []int) int {
                                                        +    stack := structures.NewArrayStack()
                                                        +    aliveFish := 0
                                                        +    for idx, val := range B {
                                                        +        if val == 1 {
                                                        +            stack.Push(A[idx])
                                                        +        } else {
                                                        +            // 繼續往下游
                                                        +            for !stack.IsEmpty() {
                                                        +                if stack.Top().(int) < A[idx] {
                                                        +                    // stack的魚比遇到的魚還小, stack被吃掉
                                                        +                    stack.Pop()
                                                        +                } else {
                                                        +                    break
                                                        +                }
                                                        +            }
                                                        +            if stack.IsEmpty() {
                                                        +                aliveFish++
                                                        +            }
                                                        +        }
                                                        +    }
                                                        +    return aliveFish + stack.Size()
                                                        +}
                                                        +
                                                        +
                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                        + + +
                                                        + +
                                                        +
                                                        +
                                                        + +

                                                        results matching ""

                                                        +
                                                          + +
                                                          +
                                                          + +

                                                          No results matching ""

                                                          + +
                                                          +
                                                          +
                                                          + +
                                                          +
                                                          + +
                                                          + + + + + + + + + + + + + + +
                                                          + + +
                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting.go b/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting.go new file mode 100644 index 000000000..78fc6c69c --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting.go @@ -0,0 +1,27 @@ +package Nesting + +import "LeetcodeGolang/Utility/structures" + +func Solution(S string) int { + if len(S) == 0 { + return 1 + } + if len(S)%2 != 0 { + return 0 + } + + stack := structures.NewArrayStack() + for _, v := range S { + val := string(v) + if val == "(" { + stack.Push(val) + } else if val == ")" { + stack.Pop() + } + } + if stack.IsEmpty() { + return 1 + } else { + return 0 + } +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting_test.go b/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting_test.go new file mode 100644 index 000000000..7b94d2282 --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting_test.go @@ -0,0 +1,25 @@ +package Nesting + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "(()(())())", + 1, + }, + { + "())", + 0, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/Nesting/index.html b/Codility/Lesson/0007.Stacks-and-Queues/Nesting/index.html new file mode 100644 index 000000000..87e505301 --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/Nesting/index.html @@ -0,0 +1,3852 @@ + + + + + + + Nesting ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                          +
                                                          + + + + + + + + +
                                                          + +
                                                          + +
                                                          + + + + + + + + +
                                                          +
                                                          + +
                                                          +
                                                          + +
                                                          + +

                                                          Nesting

                                                          +

                                                          Determine whether a given string of parentheses (single type) is properly nested.

                                                          +

                                                          A string S consisting of N characters is called properly nested if:

                                                          +

                                                          S is empty; +S has the form "(U)" where U is a properly nested string; +S has the form "VW" where V and W are properly nested strings. +For example, string "(()(())())" is properly nested but string "())" isn't.

                                                          +

                                                          Write a function:

                                                          +

                                                          func Solution(S string) int

                                                          +

                                                          that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise.

                                                          +

                                                          For example, given S = "(()(())())", the function should return 1 and given S = "())", the function should return 0, as explained above.

                                                          +

                                                          Write an efficient algorithm for the following assumptions:

                                                          +

                                                          N is an integer within the range [0..1,000,000]; +string S consists only of the characters "(" and/or ")". +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                          +

                                                          題目大意

                                                          +

                                                          括號配對

                                                          +

                                                          解題思路

                                                          +

                                                          與Bracket類似

                                                          +

                                                          來源

                                                          +

                                                          https://app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/

                                                          +

                                                          解答

                                                          +

                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting.go

                                                          +
                                                          package Nesting
                                                          +
                                                          +import "LeetcodeGolang/Utility/structures"
                                                          +
                                                          +func Solution(S string) int {
                                                          +    if len(S) == 0 {
                                                          +        return 1
                                                          +    }
                                                          +    if len(S)%2 != 0 {
                                                          +        return 0
                                                          +    }
                                                          +
                                                          +    stack := structures.NewArrayStack()
                                                          +    for _, v := range S {
                                                          +        val := string(v)
                                                          +        if val == "(" {
                                                          +            stack.Push(val)
                                                          +        } else if val == ")" {
                                                          +            stack.Pop()
                                                          +        }
                                                          +    }
                                                          +    if stack.IsEmpty() {
                                                          +        return 1
                                                          +    } else {
                                                          +        return 0
                                                          +    }
                                                          +}
                                                          +
                                                          +
                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                          + + +
                                                          + +
                                                          +
                                                          +
                                                          + +

                                                          results matching ""

                                                          +
                                                            + +
                                                            +
                                                            + +

                                                            No results matching ""

                                                            + +
                                                            +
                                                            +
                                                            + +
                                                            +
                                                            + +
                                                            + + + + + + + + + + + + + + +
                                                            + + +
                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall.go b/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall.go new file mode 100644 index 000000000..f09fcb161 --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall.go @@ -0,0 +1,18 @@ +package StoneWall + +import "LeetcodeGolang/Utility/structures" + +func Solution(H []int) int { + stack := structures.NewArrayStack() + result := 0 + for _, v := range H { + for !stack.IsEmpty() && stack.Top().(int) > v { + stack.Pop() + } + if stack.IsEmpty() || stack.Top().(int) < v { + stack.Push(v) + result++ + } + } + return result +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall_test.go b/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall_test.go new file mode 100644 index 000000000..def07317f --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall_test.go @@ -0,0 +1,21 @@ +package StoneWall + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{8, 8, 5, 7, 9, 8, 7, 4, 8}, + 7, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/index.html b/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/index.html new file mode 100644 index 000000000..9e14a4e19 --- /dev/null +++ b/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/index.html @@ -0,0 +1,3847 @@ + + + + + + + Stone Wall ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                            +
                                                            + + + + + + + + +
                                                            + +
                                                            + +
                                                            + + + + + + + + +
                                                            +
                                                            + +
                                                            +
                                                            + +
                                                            + +

                                                            StoneWall

                                                            +

                                                            Cover "Manhattan skyline" using the minimum number of rectangles.

                                                            +

                                                            You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.

                                                            +

                                                            The wall should be built of cuboid (長方體) stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.

                                                            +

                                                            Write a function:

                                                            +

                                                            func Solution(H []int) int

                                                            +

                                                            that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.

                                                            +

                                                            For example, given array H containing N = 9 integers:

                                                            +

                                                            H[0] = 8 H[1] = 8 H[2] = 5 + H[3] = 7 H[4] = 9 H[5] = 8 + H[6] = 7 H[7] = 4 H[8] = 8 +the function should return 7. The figure shows one possible arrangement of seven blocks.

                                                            +

                                                            +

                                                            Write an efficient algorithm for the following assumptions:

                                                            +

                                                            N is an integer within the range [1..100,000]; +each element of array H is an integer within the range [1..1,000,000,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                            +

                                                            題目大意

                                                            +

                                                            如何用最少的數量來貼出符合 H 的牆呢 +要建立一面長N米的強. 厚度固定, 每個地方的高度不同. +H[I]代表牆從 I 到 I+1 米處的高度. +H[0]大表牆最左到1米處的高度 +H[N-1]大表牆N-1米處到最右的高度

                                                            +

                                                            解題思路

                                                            +

                                                            尋遍整個array, 當當前高度大於先前高度時,加入stack裡, 並視為一個矩形. 將結果+1 +若當前高度小於先前,將先前高度pop出去.直到stack 為空或當前高度大於等於先前高度

                                                            +

                                                            來源

                                                            + +

                                                            解答

                                                            +

                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall.go

                                                            +
                                                            package StoneWall
                                                            +
                                                            +import "LeetcodeGolang/Utility/structures"
                                                            +
                                                            +func Solution(H []int) int {
                                                            +    stack := structures.NewArrayStack()
                                                            +    result := 0
                                                            +    for _, v := range H {
                                                            +        for !stack.IsEmpty() && stack.Top().(int) > v {
                                                            +            stack.Pop()
                                                            +        }
                                                            +        if stack.IsEmpty() || stack.Top().(int) < v {
                                                            +            stack.Push(v)
                                                            +            result++
                                                            +        }
                                                            +    }
                                                            +    return result
                                                            +}
                                                            +
                                                            +
                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                            + + +
                                                            + +
                                                            +
                                                            +
                                                            + +

                                                            results matching ""

                                                            +
                                                              + +
                                                              +
                                                              + +

                                                              No results matching ""

                                                              + +
                                                              +
                                                              +
                                                              + +
                                                              +
                                                              + +
                                                              + + + + + + + + + + +
                                                              + + +
                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0008.Leader/Dominator/Dominator.go b/Codility/Lesson/0008.Leader/Dominator/Dominator.go new file mode 100644 index 000000000..89ec30489 --- /dev/null +++ b/Codility/Lesson/0008.Leader/Dominator/Dominator.go @@ -0,0 +1,39 @@ +package Dominator + +import ( + "math" +) + +func Solution(A []int) int { + mapInt := make(map[int]int, len(A)) + + for _, v := range A { + if _, ok := mapInt[v]; !ok { + mapInt[v] = 1 + } else { + mapInt[v]++ + } + } + + maxCount := 0 + maxVal := 0 + for k, v := range mapInt { + if v > maxCount { + maxCount = v + maxVal = k + } + } + minIndex := -1 + for k, v := range A { + if v == maxVal { + minIndex = k + break + } + } + + if maxCount > int(math.Floor(float64(len(A))/2.0)) { + return minIndex + } else { + return -1 + } +} diff --git a/Codility/Lesson/0008.Leader/Dominator/Dominator_test.go b/Codility/Lesson/0008.Leader/Dominator/Dominator_test.go new file mode 100644 index 000000000..b39fe1ccd --- /dev/null +++ b/Codility/Lesson/0008.Leader/Dominator/Dominator_test.go @@ -0,0 +1,21 @@ +package Dominator + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{3, 4, 3, 2, 3, -1, 3, 3}, + 0, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0008.Leader/Dominator/index.html b/Codility/Lesson/0008.Leader/Dominator/index.html new file mode 100644 index 000000000..475f8a06f --- /dev/null +++ b/Codility/Lesson/0008.Leader/Dominator/index.html @@ -0,0 +1,3865 @@ + + + + + + + Dominator ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                              +
                                                              + + + + + + + + +
                                                              + +
                                                              + +
                                                              + + + + + + + + +
                                                              +
                                                              + +
                                                              +
                                                              + +
                                                              + +

                                                              Dominator

                                                              +

                                                              Find an index of an array such that its value occurs at more than half of indices in the array.

                                                              +

                                                              An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A.

                                                              +

                                                              For example, consider array A such that

                                                              +

                                                              A[0] = 3 A[1] = 4 A[2] = 3 + A[3] = 2 A[4] = 3 A[5] = -1 + A[6] = 3 A[7] = 3 +The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.

                                                              +

                                                              Write a function

                                                              +

                                                              func Solution(A []int) int

                                                              +

                                                              that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator.

                                                              +

                                                              For example, given array A such that

                                                              +

                                                              A[0] = 3 A[1] = 4 A[2] = 3 + A[3] = 2 A[4] = 3 A[5] = -1 + A[6] = 3 A[7] = 3 +the function may return 0, 2, 4, 6 or 7, as explained above.

                                                              +

                                                              Write an efficient algorithm for the following assumptions:

                                                              +

                                                              N is an integer within the range [0..100,000]; +each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                              +

                                                              題目大意

                                                              +

                                                              返回Array中的支配數. A的支配數是3,因為它出現在A的8個元素中的5個元素中(index為0、2、4、6和7). 而5是8的一半以上 +可以返回 0,2,4,6,7中的任一數

                                                              +

                                                              解題思路

                                                              +

                                                              用map紀錄每筆數出現次數. 取最大次數看是否有超過一半以上. +是的話返回此數任一個index, 反之返回-1

                                                              +

                                                              來源

                                                              +

                                                              https://app.codility.com/programmers/lessons/8-leader/dominator/

                                                              +

                                                              解答

                                                              +

                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0008.Leader/Dominator/Dominator.go

                                                              +
                                                              package Dominator
                                                              +
                                                              +import (
                                                              +    "math"
                                                              +)
                                                              +
                                                              +func Solution(A []int) int {
                                                              +    mapInt := make(map[int]int, len(A))
                                                              +
                                                              +    for _, v := range A {
                                                              +        if _, ok := mapInt[v]; !ok {
                                                              +            mapInt[v] = 1
                                                              +        } else {
                                                              +            mapInt[v]++
                                                              +        }
                                                              +    }
                                                              +
                                                              +    maxCount := 0
                                                              +    maxVal := 0
                                                              +    for k, v := range mapInt {
                                                              +        if v > maxCount {
                                                              +            maxCount = v
                                                              +            maxVal = k
                                                              +        }
                                                              +    }
                                                              +    minIndex := -1
                                                              +    for k, v := range A {
                                                              +        if v == maxVal {
                                                              +            minIndex = k
                                                              +            break
                                                              +        }
                                                              +    }
                                                              +
                                                              +    if maxCount > int(math.Floor(float64(len(A))/2.0)) {
                                                              +        return minIndex
                                                              +    } else {
                                                              +        return -1
                                                              +    }
                                                              +}
                                                              +
                                                              +
                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                              + + +
                                                              + +
                                                              +
                                                              +
                                                              + +

                                                              results matching ""

                                                              +
                                                                + +
                                                                +
                                                                + +

                                                                No results matching ""

                                                                + +
                                                                +
                                                                +
                                                                + +
                                                                +
                                                                + +
                                                                + + + + + + + + + + +
                                                                + + +
                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader.go b/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader.go new file mode 100644 index 000000000..0c602a601 --- /dev/null +++ b/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader.go @@ -0,0 +1,36 @@ +package EquiLeader + +func Solution(A []int) int { + leaderDict := make(map[int]int) + for i := 0; i < len(A); i++ { + if _, ok := leaderDict[A[i]]; ok { + leaderDict[A[i]]++ + } else { + leaderDict[A[i]] = 1 + } + } + + leader := 0 + times := 0 + for k, v := range leaderDict { + if v > times { + times = v + leader = k + } + } + + equiCount := 0 + count := 0 // ่ถ…้ ปๆ•ธๅทฒๅ‡บ็พ็š„ๆฌกๆ•ธ + + for index, v := range A { + if v == leader { + count++ + } + if count > (index+1)/2 && (times-count) > (len(A)-(index+1))/2 { + equiCount++ + } + + } + + return equiCount +} diff --git a/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader_test.go b/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader_test.go new file mode 100644 index 000000000..d7b688a07 --- /dev/null +++ b/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader_test.go @@ -0,0 +1,21 @@ +package EquiLeader + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{4, 3, 4, 4, 4, 2}, + 2, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0008.Leader/EquiLeader/index.html b/Codility/Lesson/0008.Leader/EquiLeader/index.html new file mode 100644 index 000000000..9f84948a3 --- /dev/null +++ b/Codility/Lesson/0008.Leader/EquiLeader/index.html @@ -0,0 +1,3880 @@ + + + + + + + Equi Leader ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                +
                                                                + + + + + + + + +
                                                                + +
                                                                + +
                                                                + + + + + + + + +
                                                                +
                                                                + +
                                                                +
                                                                + +
                                                                + +

                                                                EquiLeader

                                                                +

                                                                Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same.

                                                                +

                                                                A non-empty array A consisting of N integers is given.

                                                                +

                                                                The leader of this array is the value that occurs in more than half of the elements of A.

                                                                +

                                                                An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.

                                                                +

                                                                For example, given array A such that:

                                                                +
                                                                A[0] = 4
                                                                +A[1] = 3
                                                                +A[2] = 4
                                                                +A[3] = 4
                                                                +A[4] = 4
                                                                +A[5] = 2
                                                                +

                                                                we can find two equi leaders:

                                                                +
                                                                  +
                                                                • 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
                                                                • +
                                                                • 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. +The goal is to count the number of equi leaders.
                                                                • +
                                                                +

                                                                Write a function:

                                                                +

                                                                func Solution(A []int) int

                                                                +

                                                                that, given a non-empty array A consisting of N integers, returns the number of equi leaders.

                                                                +

                                                                For example, given:

                                                                +
                                                                A[0] = 4
                                                                +A[1] = 3
                                                                +A[2] = 4
                                                                +A[3] = 4
                                                                +A[4] = 4
                                                                +A[5] = 2
                                                                +

                                                                the function should return 2, as explained above.

                                                                +

                                                                Write an efficient algorithm for the following assumptions:

                                                                +

                                                                N is an integer within the range [1..100,000]; +each element of array A is an integer within the range [−1,000,000,000..1,000,000,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                +

                                                                題目大意

                                                                +

                                                                選定一個下標, 將一個數組分爲左右兩個子數組, 使得兩個子數組都有相同的leader, +則稱此下標爲EquiLeader, 要求返回給定數組中EquiLeader的個數n. +事實上, 若一個數同時是左子數組的leader, 它必然也是整個數組的leader.

                                                                +

                                                                解題思路

                                                                +

                                                                需要先找出序列中的leader, 記錄其出現的次數. +然後再遍歷整個數組,枚舉分割點,記錄下左子數組leader出現的次數s, +看s與n-s是否能使得leader在左右子數組中仍爲leader.

                                                                +

                                                                來源

                                                                + +

                                                                解答

                                                                +

                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader.go

                                                                +
                                                                package EquiLeader
                                                                +
                                                                +func Solution(A []int) int {
                                                                +    leaderDict := make(map[int]int)
                                                                +    for i := 0; i < len(A); i++ {
                                                                +        if _, ok := leaderDict[A[i]]; ok {
                                                                +            leaderDict[A[i]]++
                                                                +        } else {
                                                                +            leaderDict[A[i]] = 1
                                                                +        }
                                                                +    }
                                                                +
                                                                +    leader := 0
                                                                +    times := 0
                                                                +    for k, v := range leaderDict {
                                                                +        if v > times {
                                                                +            times = v
                                                                +            leader = k
                                                                +        }
                                                                +    }
                                                                +
                                                                +    equiCount := 0
                                                                +    count := 0 // 超頻數已出現的次數
                                                                +
                                                                +    for index, v := range A {
                                                                +        if v == leader {
                                                                +            count++
                                                                +        }
                                                                +        if count > (index+1)/2 && (times-count) > (len(A)-(index+1))/2 {
                                                                +            equiCount++
                                                                +        }
                                                                +
                                                                +    }
                                                                +
                                                                +    return equiCount
                                                                +}
                                                                +
                                                                +
                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                + + +
                                                                + +
                                                                +
                                                                +
                                                                + +

                                                                results matching ""

                                                                +
                                                                  + +
                                                                  +
                                                                  + +

                                                                  No results matching ""

                                                                  + +
                                                                  +
                                                                  +
                                                                  + +
                                                                  +
                                                                  + +
                                                                  + + + + + + + + + + +
                                                                  + + +
                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum.go b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum.go new file mode 100644 index 000000000..620844262 --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum.go @@ -0,0 +1,34 @@ +package MaxDoubleSliceSum + +import ( + "math" +) + +func Solution(A []int) int { + if len(A) < 4 { + return 0 + } + N := len(A) - 2 + forwardSum := make([]int, N) + reverseSum := make([]int, N) + + // 0 โ‰ค X < Y < Z < N, + // A[X + 1] + A[X + 2] + ... + A[Y โˆ’ 1] + A[Y + 1] + A[Y + 2] + ... + A[Z โˆ’ 1]. + // A : [ 3, 2, 6, -1, 4, 5, -1, 2] + // forwardSum : [ 0, 2, 8, 7, 11, 16] + // reverseSum : [14, 8, 9, 5, 0, 0] + for i := 0; i < N-1; i++ { + forwardVal := A[i+1] + reverseVal := A[N-i] + + forwardSum[i+1] = int(math.Max(0, float64(forwardVal)+float64(forwardSum[i]))) + reverseSum[N-i-2] = int(math.Max(0, float64(reverseVal)+float64(reverseSum[N-i-1]))) + } + + combineMax := math.MinInt64 + for i := 0; i < N; i++ { + combineMax = int(math.Max(float64(combineMax), float64(forwardSum[i])+float64(reverseSum[i]))) + } + + return combineMax +} diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum_test.go b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum_test.go new file mode 100644 index 000000000..9f6d4df55 --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum_test.go @@ -0,0 +1,21 @@ +package MaxDoubleSliceSum + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{3, 2, 6, -1, 4, 5, -1, 2}, + 17, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/index.html b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/index.html new file mode 100644 index 000000000..b9d1413d1 --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/index.html @@ -0,0 +1,3879 @@ + + + + + + + Max Double Slice Sum ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                  +
                                                                  + + + + + + + + +
                                                                  + +
                                                                  + +
                                                                  + + + + + + + + +
                                                                  +
                                                                  + +
                                                                  +
                                                                  + +
                                                                  + +

                                                                  MaxDoubleSliceSum

                                                                  +

                                                                  Find the maximal sum of any double slice.

                                                                  +

                                                                  A non-empty array A consisting of N integers is given.

                                                                  +

                                                                  A triplet (X, Y, Z), such that 0 ≤ X < Y < Z < N, is called a double slice.

                                                                  +

                                                                  The sum of double slice (X, Y, Z) is the total of A[X + 1] + A[X + 2] + ... + A[Y − 1] + A[Y + 1] + A[Y + 2] + ... + A[Z − 1].

                                                                  +

                                                                  For example, array A such that:

                                                                  +
                                                                  A[0] = 3
                                                                  +A[1] = 2
                                                                  +A[2] = 6
                                                                  +A[3] = -1
                                                                  +A[4] = 4
                                                                  +A[5] = 5
                                                                  +A[6] = -1
                                                                  +A[7] = 2
                                                                  +

                                                                  contains the following example double slices:

                                                                  +

                                                                  double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17, +double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 − 1 = 16, +double slice (3, 4, 5), sum is 0. +The goal is to find the maximal sum of any double slice.

                                                                  +

                                                                  Write a function:

                                                                  +

                                                                  func Solution(A []int) int

                                                                  +

                                                                  that, given a non-empty array A consisting of N integers, returns the maximal sum of any double slice.

                                                                  +

                                                                  For example, given:

                                                                  +
                                                                  A[0] = 3
                                                                  +A[1] = 2
                                                                  +A[2] = 6
                                                                  +A[3] = -1
                                                                  +A[4] = 4
                                                                  +A[5] = 5
                                                                  +A[6] = -1
                                                                  +A[7] = 2
                                                                  +

                                                                  the function should return 17, because no double slice of array A has a sum of greater than 17.

                                                                  +

                                                                  Write an efficient algorithm for the following assumptions:

                                                                  +

                                                                  N is an integer within the range [3..100,000]; +each element of array A is an integer within the range [−10,000..10,000]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                  +

                                                                  題目大意

                                                                  +

                                                                  A[X+1]到A[Y-1] + A[Y+1]到A[Z-1] 最大的和

                                                                  +

                                                                  解題思路

                                                                  +

                                                                  正向尋過array, 獲得到達每個index可以得到的最大值序列, 然后反向尋過array獲得到達每個index可以得到的最大值序列, +反向的的最大值序列需要倒轉.然後間隔一個位置, +最後尋遍array起兩者相加最大值

                                                                  +

                                                                  來源

                                                                  + +

                                                                  解答

                                                                  +

                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum.go

                                                                  +
                                                                  package MaxDoubleSliceSum
                                                                  +
                                                                  +import (
                                                                  +    "math"
                                                                  +)
                                                                  +
                                                                  +func Solution(A []int) int {
                                                                  +    if len(A) < 4 {
                                                                  +        return 0
                                                                  +    }
                                                                  +    N := len(A) - 2
                                                                  +    forwardSum := make([]int, N)
                                                                  +    reverseSum := make([]int, N)
                                                                  +
                                                                  +    //  0 ≤ X < Y < Z < N,
                                                                  +    //  A[X + 1] + A[X + 2] + ... + A[Y − 1] + A[Y + 1] + A[Y + 2] + ... + A[Z − 1].
                                                                  +    //             A : [ 3,  2, 6, -1,  4,  5, -1, 2]
                                                                  +    // forwardSum : [ 0,  2, 8,  7, 11, 16]
                                                                  +    // reverseSum : [14,  8, 9,  5,  0,  0]
                                                                  +    for i := 0; i < N-1; i++ {
                                                                  +        forwardVal := A[i+1]
                                                                  +        reverseVal := A[N-i]
                                                                  +
                                                                  +        forwardSum[i+1] = int(math.Max(0, float64(forwardVal)+float64(forwardSum[i])))
                                                                  +        reverseSum[N-i-2] = int(math.Max(0, float64(reverseVal)+float64(reverseSum[N-i-1])))
                                                                  +    }
                                                                  +
                                                                  +    combineMax := math.MinInt64
                                                                  +    for i := 0; i < N; i++ {
                                                                  +        combineMax = int(math.Max(float64(combineMax), float64(forwardSum[i])+float64(reverseSum[i])))
                                                                  +    }
                                                                  +
                                                                  +    return combineMax
                                                                  +}
                                                                  +
                                                                  +
                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                  + + +
                                                                  + +
                                                                  +
                                                                  +
                                                                  + +

                                                                  results matching ""

                                                                  +
                                                                    + +
                                                                    +
                                                                    + +

                                                                    No results matching ""

                                                                    + +
                                                                    +
                                                                    +
                                                                    + +
                                                                    +
                                                                    + +
                                                                    + + + + + + + + + + +
                                                                    + + +
                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit.go b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit.go new file mode 100644 index 000000000..618abdc07 --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit.go @@ -0,0 +1,17 @@ +package MaxProfit + +import ( + "math" +) + +func Solution(A []int) int { + minBuyPrice := math.MaxFloat64 + maxProfit := 0.0 + + for _, v := range A { + minBuyPrice = math.Min(minBuyPrice, float64(v)) + maxProfit = math.Max(maxProfit, float64(v)-minBuyPrice) + } + + return int(maxProfit) +} diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit_test.go b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit_test.go new file mode 100644 index 000000000..ccfdde7de --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit_test.go @@ -0,0 +1,21 @@ +package MaxProfit + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{23171, 21011, 21123, 21366, 21013, 21367}, + 356, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/index.html b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/index.html new file mode 100644 index 000000000..7b752ca01 --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/index.html @@ -0,0 +1,3853 @@ + + + + + + + Max Profit ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                    +
                                                                    + + + + + + + + +
                                                                    + +
                                                                    + +
                                                                    + + + + + + + + +
                                                                    +
                                                                    + +
                                                                    +
                                                                    + +
                                                                    + +

                                                                    MaxProfit

                                                                    +

                                                                    Given a log of stock prices compute the maximum possible earning.

                                                                    +

                                                                    An array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 ≤ P ≤ Q < N, then the profit of such transaction is equal to A[Q] − A[P], provided that A[Q] ≥ A[P]. Otherwise, the transaction brings loss of A[P] − A[Q].

                                                                    +

                                                                    For example, consider the following array A consisting of six elements such that:

                                                                    +

                                                                    A[0] = 23171 + A[1] = 21011 + A[2] = 21123 + A[3] = 21366 + A[4] = 21013 + A[5] = 21367 +If a share was bought on day 0 and sold on day 2, a loss of 2048 would occur because A[2] − A[0] = 21123 − 23171 = −2048. If a share was bought on day 4 and sold on day 5, a profit of 354 would occur because A[5] − A[4] = 21367 − 21013 = 354. Maximum possible profit was 356. It would occur if a share was bought on day 1 and sold on day 5.

                                                                    +

                                                                    Write a function,

                                                                    +

                                                                    func Solution(A []int) int

                                                                    +

                                                                    that, given an array A consisting of N integers containing daily prices of a stock share for a period of N consecutive days, returns the maximum possible profit from one transaction during this period. The function should return 0 if it was impossible to gain any profit.

                                                                    +

                                                                    For example, given array A consisting of six elements such that:

                                                                    +

                                                                    A[0] = 23171 + A[1] = 21011 + A[2] = 21123 + A[3] = 21366 + A[4] = 21013 + A[5] = 21367 +the function should return 356, as explained above.

                                                                    +

                                                                    Write an efficient algorithm for the following assumptions:

                                                                    +

                                                                    N is an integer within the range [0..400,000]; +each element of array A is an integer within the range [0..200,000].

                                                                    +

                                                                    Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                    +

                                                                    題目大意

                                                                    +

                                                                    計算股票可能獲得的最大利潤

                                                                    +

                                                                    解題思路

                                                                    +

                                                                    尋遍整個array, 找出最小的買入金額, 同時計算當前的賣出金額-最小買入金額, 得出最大利潤

                                                                    +

                                                                    來源

                                                                    +

                                                                    https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/

                                                                    +

                                                                    解答

                                                                    +

                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit.go

                                                                    +
                                                                    package MaxProfit
                                                                    +
                                                                    +import (
                                                                    +    "math"
                                                                    +)
                                                                    +
                                                                    +func Solution(A []int) int {
                                                                    +    minBuyPrice := math.MaxFloat64
                                                                    +    maxProfit := 0.0
                                                                    +
                                                                    +    for _, v := range A {
                                                                    +        minBuyPrice = math.Min(minBuyPrice, float64(v))
                                                                    +        maxProfit = math.Max(maxProfit, float64(v)-minBuyPrice)
                                                                    +    }
                                                                    +
                                                                    +    return int(maxProfit)
                                                                    +}
                                                                    +
                                                                    +
                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                    + + +
                                                                    + +
                                                                    +
                                                                    +
                                                                    + +

                                                                    results matching ""

                                                                    +
                                                                      + +
                                                                      +
                                                                      + +

                                                                      No results matching ""

                                                                      + +
                                                                      +
                                                                      +
                                                                      + +
                                                                      +
                                                                      + +
                                                                      + + + + + + + + + + + + + + +
                                                                      + + +
                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum.go b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum.go new file mode 100644 index 000000000..5f738eabc --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum.go @@ -0,0 +1,18 @@ +package MaxSliceSum + +import ( + "math" +) + +func Solution(A []int) int { + if len(A) == 1 { + return A[0] + } + result := math.MinInt64 + sum := math.MinInt64 + for i := 0; i < len(A); i++ { + sum = int(math.Max(float64(A[i]), float64(A[i])+float64(sum))) + result = int(math.Max(float64(sum), float64(result))) + } + return result +} diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum_test.go b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum_test.go new file mode 100644 index 000000000..bc0211e50 --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum_test.go @@ -0,0 +1,25 @@ +package MaxSliceSum + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{3, 2, -6, 4, 0}, + 5, + }, + // { + // []int{-2, -2}, + // -2, + // }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/index.html b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/index.html new file mode 100644 index 000000000..521038248 --- /dev/null +++ b/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/index.html @@ -0,0 +1,3842 @@ + + + + + + + Max Slice Sum ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                      +
                                                                      + + + + + + + + +
                                                                      + +
                                                                      + +
                                                                      + + + + + + + + +
                                                                      +
                                                                      + +
                                                                      +
                                                                      + +
                                                                      + +

                                                                      MaxSliceSum

                                                                      +

                                                                      Find a maximum sum of a compact subsequence of array elements.

                                                                      +

                                                                      A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N, is called a slice of array A. The sum of a slice (P, Q) is the total of A[P] + A[P+1] + ... + A[Q].

                                                                      +

                                                                      Write a function:

                                                                      +

                                                                      func Solution(A []int) int

                                                                      +

                                                                      that, given an array A consisting of N integers, returns the maximum sum of any slice of A.

                                                                      +

                                                                      For example, given array A such that:

                                                                      +

                                                                      A[0] = 3 A[1] = 2 A[2] = -6 +A[3] = 4 A[4] = 0 +the function should return 5 because:

                                                                      +

                                                                      (3, 4) is a slice of A that has sum 4, +(2, 2) is a slice of A that has sum −6, +(0, 1) is a slice of A that has sum 5, +no other slice of A has sum greater than (0, 1). +Write an efficient algorithm for the following assumptions:

                                                                      +

                                                                      N is an integer within the range [1..1,000,000]; +each element of array A is an integer within the range [−1,000,000..1,000,000]; +the result will be an integer within the range [−2,147,483,648..2,147,483,647].

                                                                      +

                                                                      Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                      +

                                                                      題目大意

                                                                      +

                                                                      找出連續子序列最大的和

                                                                      +

                                                                      解題思路

                                                                      +

                                                                      長度如果為1, 回傳第一筆 +當下的值跟當下的值加上先前的和, 取最大值. 再將剛剛算出的最大值跟紀錄中的最大值比較,取最大值

                                                                      +

                                                                      來源

                                                                      +

                                                                      https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/

                                                                      +

                                                                      解答

                                                                      +

                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum.go

                                                                      +
                                                                      package MaxSliceSum
                                                                      +
                                                                      +import (
                                                                      +    "math"
                                                                      +)
                                                                      +
                                                                      +func Solution(A []int) int {
                                                                      +    if len(A) == 1 {
                                                                      +        return A[0]
                                                                      +    }
                                                                      +    result := math.MinInt64
                                                                      +    sum := math.MinInt64
                                                                      +    for i := 0; i < len(A); i++ {
                                                                      +        sum = int(math.Max(float64(A[i]), float64(A[i])+float64(sum)))
                                                                      +        result = int(math.Max(float64(sum), float64(result)))
                                                                      +    }
                                                                      +    return result
                                                                      +}
                                                                      +
                                                                      +
                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                      + + +
                                                                      + +
                                                                      +
                                                                      +
                                                                      + +

                                                                      results matching ""

                                                                      +
                                                                        + +
                                                                        +
                                                                        + +

                                                                        No results matching ""

                                                                        + +
                                                                        +
                                                                        +
                                                                        + +
                                                                        +
                                                                        + +
                                                                        + + + + + + + + + + +
                                                                        + + +
                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors.go new file mode 100644 index 000000000..9a2250848 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors.go @@ -0,0 +1,21 @@ +package CountFactors + +import ( + "math" +) + +func Solution(N int) int { + result := 0 + for i := 1; i <= int(math.Pow(float64(N), 0.5)); i++ { + if N%i == 0 { + if i*i == N { + // fmt.Println("+1 : ", i) + result++ + } else { + // fmt.Println("+2 : ", i) + result += 2 + } + } + } + return result +} diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors_test.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors_test.go new file mode 100644 index 000000000..34608d047 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors_test.go @@ -0,0 +1,21 @@ +package CountFactors + +import "testing" + +var tests = []struct { + arg1 int + want int +}{ + { + 24, + 8, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/index.html b/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/index.html new file mode 100644 index 000000000..36d07fcc5 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/index.html @@ -0,0 +1,3823 @@ + + + + + + + Count Factors ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                        +
                                                                        + + + + + + + + +
                                                                        + +
                                                                        + +
                                                                        + + + + + + + + +
                                                                        +
                                                                        + +
                                                                        +
                                                                        + +
                                                                        + +

                                                                        CountFactors

                                                                        +

                                                                        Count factors of given number n.

                                                                        +

                                                                        A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M.

                                                                        +

                                                                        For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4).

                                                                        +

                                                                        Write a function:

                                                                        +

                                                                        func Solution(N int) int

                                                                        +

                                                                        that, given a positive integer N, returns the number of its factors.

                                                                        +

                                                                        For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24.

                                                                        +

                                                                        Write an efficient algorithm for the following assumptions:

                                                                        +

                                                                        N is an integer within the range [1..2,147,483,647].

                                                                        +

                                                                        Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                        +

                                                                        題目大意

                                                                        +

                                                                        找出該數的因子個數

                                                                        +

                                                                        解題思路

                                                                        +

                                                                        尋遍該數字平方根的整數, 每次可以獲得2個因子

                                                                        +

                                                                        來源

                                                                        +

                                                                        https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/count_factors/

                                                                        +

                                                                        解答

                                                                        +

                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors.go

                                                                        +
                                                                        package CountFactors
                                                                        +
                                                                        +import (
                                                                        +    "math"
                                                                        +)
                                                                        +
                                                                        +func Solution(N int) int {
                                                                        +    result := 0
                                                                        +    for i := 1; i 
                                                                        +
                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                        + + +
                                                                        + +
                                                                        +
                                                                        +
                                                                        + +

                                                                        results matching ""

                                                                        +
                                                                          + +
                                                                          +
                                                                          + +

                                                                          No results matching ""

                                                                          + +
                                                                          +
                                                                          +
                                                                          + +
                                                                          +
                                                                          + +
                                                                          + + + + + + + + + + +
                                                                          + + +
                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags.go new file mode 100644 index 000000000..d02e61489 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags.go @@ -0,0 +1,38 @@ +package Flags + +import ( + "math" +) + +func Solution(A []int) int { + var peaksFlag []int + + for i := 1; i < len(A)-1; i++ { + if A[i] > A[i-1] && A[i] > A[i+1] { + peaksFlag = append(peaksFlag, i) + } + } + + if len(peaksFlag) == 0 { + return 0 + } + if len(peaksFlag) == 1 { + return 1 + } + + maxFlag := int(math.Pow(float64(peaksFlag[len(peaksFlag)-1]-peaksFlag[0]), 0.5) + 1) + + for i := maxFlag; i > 1; i-- { + addressFlag := []int{peaksFlag[0]} + for _, val := range peaksFlag[1:] { + if val-addressFlag[len(addressFlag)-1] >= i { + addressFlag = append(addressFlag, val) + if len(addressFlag) >= i { + return i + } + } + } + } + + return 1 +} diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags_test.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags_test.go new file mode 100644 index 000000000..48994a714 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags_test.go @@ -0,0 +1,21 @@ +package Flags + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2}, + 3, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/index.html b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/index.html new file mode 100644 index 000000000..3a14a2d81 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/index.html @@ -0,0 +1,3900 @@ + + + + + + + Flags ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                          +
                                                                          + + + + + + + + +
                                                                          + +
                                                                          + +
                                                                          + + + + + + + + +
                                                                          +
                                                                          + +
                                                                          +
                                                                          + +
                                                                          + +

                                                                          Flags

                                                                          +

                                                                          Find the maximum number of flags that can be set on mountain peaks.

                                                                          +

                                                                          A non-empty array A consisting of N integers is given.

                                                                          +

                                                                          A peak is an array element which is larger than its neighbours. More precisely, it is an index P such that 0 < P < N − 1 and A[P − 1] < A[P] > A[P + 1].

                                                                          +

                                                                          For example, the following array A:

                                                                          +
                                                                          A[0] = 1
                                                                          +A[1] = 5 //peaks
                                                                          +A[2] = 3
                                                                          +A[3] = 4 //peaks
                                                                          +A[4] = 3
                                                                          +A[5] = 4 //peaks
                                                                          +A[6] = 1
                                                                          +A[7] = 2
                                                                          +A[8] = 3
                                                                          +A[9] = 4
                                                                          +A[10] = 6 //peaks
                                                                          +A[11] = 2
                                                                          +

                                                                          has exactly four peaks: elements 1, 3, 5 and 10.

                                                                          +

                                                                          You are going on a trip to a range of mountains whose relative heights are represented by array A, as shown in a figure below. You have to choose how many flags you should take with you. The goal is to set the maximum number of flags on the peaks, according to certain rules.

                                                                          +

                                                                          +

                                                                          Flags can only be set on peaks. What's more, if you take K flags, then the distance between any two flags should be greater than or equal to K. The distance between indices P and Q is the absolute value |P − Q|.

                                                                          +

                                                                          For example, given the mountain range represented by array A, above, with N = 12, if you take:

                                                                          +

                                                                          two flags, you can set them on peaks 1 and 5; +three flags, you can set them on peaks 1, 5 and 10; +four flags, you can set only three flags, on peaks 1, 5 and 10. +You can therefore set a maximum of three flags in this case.

                                                                          +

                                                                          Write a function:

                                                                          +

                                                                          func Solution(A []int) int

                                                                          +

                                                                          that, given a non-empty array A of N integers, returns the maximum number of flags that can be set on the peaks of the array.

                                                                          +

                                                                          For example, the following array A:

                                                                          +
                                                                          A[0] = 1
                                                                          +A[1] = 5
                                                                          +A[2] = 3
                                                                          +A[3] = 4
                                                                          +A[4] = 3
                                                                          +A[5] = 4
                                                                          +A[6] = 1
                                                                          +A[7] = 2
                                                                          +A[8] = 3
                                                                          +A[9] = 4
                                                                          +A[10] = 6
                                                                          +A[11] = 2
                                                                          +

                                                                          the function should return 3, as explained above.

                                                                          +

                                                                          Write an efficient algorithm for the following assumptions:

                                                                          +

                                                                          N is an integer within the range [1..400,000]; +each element of array A is an integer within the range [0..1,000,000,000].

                                                                          +

                                                                          Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                          +

                                                                          題目大意

                                                                          +

                                                                          計算可以在山峰上設置的最大旗標數量 +旗標只能在山峰上設置, 如果帶了K個旗標, 則任意兩個旗標的索引距離不能小於K

                                                                          +

                                                                          解題思路

                                                                          +

                                                                          先找出peak的索引位置並存入array中. 根據peak array的第一個最後一個可以判斷理論上最多的旗標數為K: K*(K-1)<=P[-1] - P[0]=dis, 所以K的最大值為 int(sqrt(P[-1] - P[0]) +1). +然後從K的最大值開始找, 尋遍peak array, 只要滿足距離大於等於就將旗標存入旗標array, 只要旗標array數不小於K值,就返回

                                                                          +

                                                                          來源

                                                                          + +

                                                                          解答

                                                                          +

                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags.go

                                                                          +
                                                                          package Flags
                                                                          +
                                                                          +import (
                                                                          +    "math"
                                                                          +)
                                                                          +
                                                                          +func Solution(A []int) int {
                                                                          +    var peaksFlag []int
                                                                          +
                                                                          +    for i := 1; i < len(A)-1; i++ {
                                                                          +        if A[i] > A[i-1] && A[i] > A[i+1] {
                                                                          +            peaksFlag = append(peaksFlag, i)
                                                                          +        }
                                                                          +    }
                                                                          +
                                                                          +    if len(peaksFlag) == 0 {
                                                                          +        return 0
                                                                          +    }
                                                                          +    if len(peaksFlag) == 1 {
                                                                          +        return 1
                                                                          +    }
                                                                          +
                                                                          +    maxFlag := int(math.Pow(float64(peaksFlag[len(peaksFlag)-1]-peaksFlag[0]), 0.5) + 1)
                                                                          +
                                                                          +    for i := maxFlag; i > 1; i-- {
                                                                          +        addressFlag := []int{peaksFlag[0]}
                                                                          +        for _, val := range peaksFlag[1:] {
                                                                          +            if val-addressFlag[len(addressFlag)-1] >= i {
                                                                          +                addressFlag = append(addressFlag, val)
                                                                          +                if len(addressFlag) >= i {
                                                                          +                    return i
                                                                          +                }
                                                                          +            }
                                                                          +        }
                                                                          +    }
                                                                          +
                                                                          +    return 1
                                                                          +}
                                                                          +
                                                                          +
                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                          + + +
                                                                          + +
                                                                          +
                                                                          +
                                                                          + +

                                                                          results matching ""

                                                                          +
                                                                            + +
                                                                            +
                                                                            + +

                                                                            No results matching ""

                                                                            + +
                                                                            +
                                                                            +
                                                                            + +
                                                                            +
                                                                            + +
                                                                            + + + + + + + + + + + + + + +
                                                                            + + +
                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle.go new file mode 100644 index 000000000..735b84b38 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle.go @@ -0,0 +1,77 @@ +package minperimeterrectangle + +import ( + "math" +) + +// O(sqrt(N)) +func Solution(N int) int { + if N <= 0 { + return 0 + } + + min := math.MaxInt32 + for i := 1; i*i <= N; i++ { + if N%i == 0 { + perimeter := 2 * (i + N/i) + min = int(math.Min(float64(min), float64(perimeter))) + } + + } + + if min == math.MaxInt32 { + return 0 + } + return min +} + +/* +O(N) +Task Score 60% +Correctness 100% +Performance 20% +*/ +func Solution1(N int) int { + if N <= 0 { + return 0 + } + + min := math.MaxInt32 + for i := 1; i <= N; i++ { + if N%i == 0 && i*i <= N { + perimeter := 2 * (i + N/i) + min = int(math.Min(float64(min), float64(perimeter))) + } + } + if min == math.MaxInt32 { + return 0 + } + return min +} + +// O(sqrt(N)) +func Solution2(N int) int { + if N <= 0 { + return 0 + } + pairs := make(map[int]int) + i := 1 + for i*i <= N { + if N%i == 0 { + pairs[i] = N / i + } + i++ + } + + min := math.MaxInt32 + for i, v := range pairs { + perimeter := 2 * (i + v) + min = int(math.Min(float64(min), float64(perimeter))) + + } + + if min == math.MaxInt32 { + return 0 + } + return min +} diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle_test.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle_test.go new file mode 100644 index 000000000..58876bef5 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle_test.go @@ -0,0 +1,45 @@ +package minperimeterrectangle + +import "testing" + +var tests = []struct { + arg1 int + want int +}{ + { + 30, + 22, + }, + { + 1, + 4, + }, + { + 36, + 24, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolution1(t *testing.T) { + for _, tt := range tests { + if got := Solution1(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolution2(t *testing.T) { + for _, tt := range tests { + if got := Solution2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/index.html b/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/index.html new file mode 100644 index 000000000..7a5f05051 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/index.html @@ -0,0 +1,3838 @@ + + + + + + + Min Perimeter Rectangle ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                            +
                                                                            + + + + + + + + +
                                                                            + +
                                                                            + +
                                                                            + + + + + + + + +
                                                                            +
                                                                            + +
                                                                            +
                                                                            + +
                                                                            + +

                                                                            MinPerimeterRectangle

                                                                            +

                                                                            Find the minimal perimeter of any rectangle whose area equals N.

                                                                            +

                                                                            An integer N is given, representing the area of some rectangle.

                                                                            +

                                                                            The area of a rectangle whose sides are of length A and B is A B, and the perimeter is 2 (A + B).

                                                                            +

                                                                            The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers.

                                                                            +

                                                                            For example, given integer N = 30, rectangles of area 30 are:

                                                                            +

                                                                            (1, 30), with a perimeter of 62, +(2, 15), with a perimeter of 34, +(3, 10), with a perimeter of 26, +(5, 6), with a perimeter of 22. +Write a function:

                                                                            +

                                                                            func Solution(N int) int

                                                                            +

                                                                            that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N.

                                                                            +

                                                                            For example, given an integer N = 30, the function should return 22, as explained above.

                                                                            +

                                                                            Write an efficient algorithm for the following assumptions:

                                                                            +

                                                                            N is an integer within the range [1..1,000,000,000].

                                                                            +

                                                                            Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                            +

                                                                            題目大意

                                                                            +

                                                                            給整數的面積N, 找出面積為N的最小周長

                                                                            +

                                                                            解題思路

                                                                            +

                                                                            從不大於N的平方根的數開始遍歷,只要找到N的因子 +因為越往後所得的周長越大.邊長接近平方根的矩形的周長是最小的

                                                                            +

                                                                            來源

                                                                            + +

                                                                            解答

                                                                            +

                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle.go

                                                                            +
                                                                            package minperimeterrectangle
                                                                            +
                                                                            +import (
                                                                            +    "math"
                                                                            +)
                                                                            +
                                                                            +// O(sqrt(N))
                                                                            +func Solution(N int) int {
                                                                            +    if N 
                                                                            +
                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                            + + +
                                                                            + +
                                                                            +
                                                                            +
                                                                            + +

                                                                            results matching ""

                                                                            +
                                                                              + +
                                                                              +
                                                                              + +

                                                                              No results matching ""

                                                                              + +
                                                                              +
                                                                              +
                                                                              + +
                                                                              +
                                                                              + +
                                                                              + + + + + + + + + + + + + + +
                                                                              + + +
                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks.go new file mode 100644 index 000000000..3e1d3231a --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks.go @@ -0,0 +1,70 @@ +package peaks + +/* +expected worst-case time complexity is O(N*log(log(N))); +expected worst-case space complexity is O(N) +*/ +func Solution(A []int) int { + // ๅ…ˆๆ‰พๅ‡บpeaks + peaks := []int{} + for i := 1; i < len(A)-1; i++ { + if A[i-1] < A[i] && A[i] > A[i+1] { + peaks = append(peaks, i) + } + } + + if len(peaks) < 0 { + return 0 + } else if len(peaks) == 1 { + return 1 + } + + for size := len(peaks); size > 0; size-- { + if len(A)%size == 0 { + // ๆฏๅ€‹ๅ€ๅกŠ็š„size + blockSize := len(A) / size + found := make(map[int]bool, size) + foundCnt := 0 + for _, peak := range peaks { + // ๆชขๆŸฅๆฏๅ€‹ๅ€ๅกŠๆ˜ฏๅฆๆœ‰ๆ‰พๅˆฐ peak + blockNr := peak / blockSize + if ok := found[blockNr]; !ok { + found[blockNr] = true + foundCnt++ + } + } + if foundCnt == size { + return size + } + } + } + return 0 +} + +/* +def solution(A): + peaks = [] + + for idx in range(1, len(A)-1): + if A[idx-1] < A[idx] > A[idx+1]: + peaks.append(idx) + + if len(peaks) == 0: + return 0 + + for size in range(len(peaks), 0, -1): + if len(A) % size == 0: + block_size = len(A) // size + found = [False] * size + found_cnt = 0 + for peak in peaks: + block_nr = peak//block_size + if found[block_nr] == False: + found[block_nr] = True + found_cnt += 1 + + if found_cnt == size: + return size + + return 0 +*/ diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks_test.go b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks_test.go new file mode 100644 index 000000000..691117a76 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks_test.go @@ -0,0 +1,21 @@ +package peaks + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2}, + 3, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/index.html b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/index.html new file mode 100644 index 000000000..1434ff3e0 --- /dev/null +++ b/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/index.html @@ -0,0 +1,3932 @@ + + + + + + + Peaks ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                              +
                                                                              + + + + + + + + +
                                                                              + +
                                                                              + +
                                                                              + + + + + + + + +
                                                                              +
                                                                              + +
                                                                              +
                                                                              + +
                                                                              + +

                                                                              Peaks

                                                                              +

                                                                              Divide an array into the maximum number of same-sized blocks, each of which should contain an index P such that A[P - 1] < A[P] > A[P + 1].

                                                                              +

                                                                              A non-empty array A consisting of N integers is given.

                                                                              +

                                                                              A peak is an array element which is larger than its neighbors. More precisely, it is an index P such that 0 < P < N − 1, A[P − 1] < A[P] and A[P] > A[P + 1].

                                                                              +

                                                                              For example, the following array A:

                                                                              +
                                                                              A[0] = 1
                                                                              +A[1] = 2
                                                                              +A[2] = 3
                                                                              +A[3] = 4
                                                                              +A[4] = 3
                                                                              +A[5] = 4
                                                                              +A[6] = 1
                                                                              +A[7] = 2
                                                                              +A[8] = 3
                                                                              +A[9] = 4
                                                                              +A[10] = 6
                                                                              +A[11] = 2
                                                                              +

                                                                              has exactly three peaks: 3, 5, 10.

                                                                              +

                                                                              We want to divide this array into blocks containing the same number of elements. More precisely, we want to choose a number K that will yield the following blocks:

                                                                              +

                                                                              A[0], A[1], ..., A[K − 1], +A[K], A[K + 1], ..., A[2K − 1], +... +A[N − K], A[N − K + 1], ..., A[N − 1]. +What's more, every block should contain at least one peak. Notice that extreme elements of the blocks (for example A[K − 1] or A[K]) can also be peaks, but only if they have both neighbors (including one in an adjacent blocks).

                                                                              +

                                                                              The goal is to find the maximum number of blocks into which the array A can be divided.

                                                                              +

                                                                              Array A can be divided into blocks as follows:

                                                                              +

                                                                              one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks. +two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak. +three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block has a peak. Notice in particular that the first block (1, 2, 3, 4) has a peak at A[3], because A[2] < A[3] > A[4], even though A[4] is in the adjacent block. +However, array A cannot be divided into four blocks, (1, 2, 3), (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do not contain a peak. Notice in particular that the (4, 3, 4) block contains two peaks: A[3] and A[5].

                                                                              +

                                                                              The maximum number of blocks that array A can be divided into is three.

                                                                              +

                                                                              Write a function:

                                                                              +

                                                                              func Solution(A []int) int

                                                                              +

                                                                              that, given a non-empty array A consisting of N integers, returns the maximum number of blocks into which A can be divided.

                                                                              +

                                                                              If A cannot be divided into some number of blocks, the function should return 0.

                                                                              +

                                                                              For example, given:

                                                                              +
                                                                              A[0] = 1
                                                                              +A[1] = 2
                                                                              +A[2] = 3
                                                                              +A[3] = 4
                                                                              +A[4] = 3
                                                                              +A[5] = 4
                                                                              +A[6] = 1
                                                                              +A[7] = 2
                                                                              +A[8] = 3
                                                                              +A[9] = 4
                                                                              +A[10] = 6
                                                                              +A[11] = 2
                                                                              +

                                                                              the function should return 3, as explained above.

                                                                              +

                                                                              Write an efficient algorithm for the following assumptions:

                                                                              +

                                                                              N is an integer within the range [1..100,000]; +each element of array A is an integer within the range [0..1,000,000,000].

                                                                              +

                                                                              Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                              +

                                                                              題目大意

                                                                              +

                                                                              將 array 分成同樣長度的區塊, 買個區塊至少包含一個peak.

                                                                              +

                                                                              解題思路

                                                                              +

                                                                              先找出所有peak的index 寫入peaks array. +從peaks的長度開始往下找, 將 A 拆成區塊, +每個區塊檢查是否有有找到peak

                                                                              +

                                                                              來源

                                                                              + +

                                                                              解答

                                                                              +

                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks.go

                                                                              +
                                                                              package peaks
                                                                              +
                                                                              +/*
                                                                              +expected worst-case time complexity is O(N*log(log(N)));
                                                                              +expected worst-case space complexity is O(N)
                                                                              +*/
                                                                              +func Solution(A []int) int {
                                                                              +    // 先找出peaks
                                                                              +    peaks := []int{}
                                                                              +    for i := 1; i < len(A)-1; i++ {
                                                                              +        if A[i-1] < A[i] && A[i] > A[i+1] {
                                                                              +            peaks = append(peaks, i)
                                                                              +        }
                                                                              +    }
                                                                              +
                                                                              +    if len(peaks) < 0 {
                                                                              +        return 0
                                                                              +    } else if len(peaks) == 1 {
                                                                              +        return 1
                                                                              +    }
                                                                              +
                                                                              +    for size := len(peaks); size > 0; size-- {
                                                                              +        if len(A)%size == 0 {
                                                                              +            // 每個區塊的size
                                                                              +            blockSize := len(A) / size
                                                                              +            found := make(map[int]bool, size)
                                                                              +            foundCnt := 0
                                                                              +            for _, peak := range peaks {
                                                                              +                // 檢查每個區塊是否有找到 peak
                                                                              +                blockNr := peak / blockSize
                                                                              +                if ok := found[blockNr]; !ok {
                                                                              +                    found[blockNr] = true
                                                                              +                    foundCnt++
                                                                              +                }
                                                                              +            }
                                                                              +            if foundCnt == size {
                                                                              +                return size
                                                                              +            }
                                                                              +        }
                                                                              +    }
                                                                              +    return 0
                                                                              +}
                                                                              +
                                                                              +/*
                                                                              +def solution(A):
                                                                              +    peaks = []
                                                                              +
                                                                              +    for idx in range(1, len(A)-1):
                                                                              +        if A[idx-1] < A[idx] > A[idx+1]:
                                                                              +            peaks.append(idx)
                                                                              +
                                                                              +    if len(peaks) == 0:
                                                                              +        return 0
                                                                              +
                                                                              +    for size in range(len(peaks), 0, -1):
                                                                              +        if len(A) % size == 0:
                                                                              +            block_size = len(A) // size
                                                                              +            found = [False] * size
                                                                              +            found_cnt = 0
                                                                              +            for peak in peaks:
                                                                              +                block_nr = peak//block_size
                                                                              +                if found[block_nr] == False:
                                                                              +                    found[block_nr] = True
                                                                              +                    found_cnt += 1
                                                                              +
                                                                              +            if found_cnt == size:
                                                                              +                return size
                                                                              +
                                                                              +    return 0
                                                                              +*/
                                                                              +
                                                                              +
                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                              + + +
                                                                              + +
                                                                              +
                                                                              +
                                                                              + +

                                                                              results matching ""

                                                                              +
                                                                                + +
                                                                                +
                                                                                + +

                                                                                No results matching ""

                                                                                + +
                                                                                +
                                                                                +
                                                                                + +
                                                                                +
                                                                                + +
                                                                                + + + + + + + + + + +
                                                                                + + +
                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible.go b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible.go new file mode 100644 index 000000000..a84a605fc --- /dev/null +++ b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible.go @@ -0,0 +1,137 @@ +package countnondivisible + +import ( + "math" +) + +/* +Task Score 100% +Correctness 100% +Performance 100% +*/ +func Solution(A []int) []int { + // write your code in Go 1.4 + result := []int{} + if len(A) < 0 { + return result + } + + elementDict := make(map[int]int) + for _, i := range A { + elementDict[i]++ + } + + // ็”จ mapๅญ˜่ตท้žๅ› ๅญๆ•ธ็š„ๅ€‹ๆ•ธ, ็ฉบ้–“ๆ›ๅ–ๆ™‚้–“ + nonDivisorsCountMap := make(map[int]int) + for _, val := range A { + if v, ok := nonDivisorsCountMap[val]; ok { + result = append(result, v) + } else { + divisors := 0 + for factor := 1; factor*factor <= val; factor++ { + if val%factor == 0 { + // ๆชขๆŸฅๆ˜ฏๅฆๆœ‰ๅœจๅŽŸๅ…ˆ็š„ array ไธญ, ไธฆๅ–ๅพ—ๅ› ๅญๆฌกๆ•ธ + if v, ok := elementDict[factor]; ok { + divisors += v + } + + // ้ฟๅ…ๅ› ๅญ้‡่ค‡่จˆ็ฎ— + otherFactor := int(val / factor) + if v, ok := elementDict[otherFactor]; ok && otherFactor != factor { + divisors += v + } + } + } + // ๆŽจๅ‡บ้žๅ› ๅญๆฌกๆ•ธ + nonDivisors := len(A) - divisors + result = append(result, nonDivisors) + nonDivisorsCountMap[val] = nonDivisors + } + } + return result +} + +/* +Task Score 88% +Correctness 100% +Performance 75% +*/ +func Solution2(A []int) []int { + result := []int{} + if len(A) < 0 { + return result + } + + elementDict := make(map[int]int) + for _, i := range A { + elementDict[i]++ + } + + // ็”จ mapๅญ˜่ตท้žๅ› ๅญๆ•ธ็š„ๅ€‹ๆ•ธ, ็ฉบ้–“ๆ›ๅ–ๆ™‚้–“ + nonDivisorsCountMap := make(map[int]int) + for _, val := range A { + if v, ok := nonDivisorsCountMap[val]; ok { + result = append(result, v) + } else { + divisors := 0 + for factor := 1; factor <= int(math.Pow(float64(val), 0.5)); factor++ { + if val%factor == 0 { + // ๆชขๆŸฅๆ˜ฏๅฆๆœ‰ๅœจๅŽŸๅ…ˆ็š„ array ไธญ, ไธฆๅ–ๅพ—ๅ› ๅญๆฌกๆ•ธ + if v, ok := elementDict[factor]; ok { + divisors += v + } + + // ้ฟๅ…ๅ› ๅญ้‡่ค‡่จˆ็ฎ— + otherFactor := int(val / factor) + if v, ok := elementDict[otherFactor]; ok && otherFactor != factor { + divisors += v + } + } + } + // ๆŽจๅ‡บ้žๅ› ๅญๆฌกๆ•ธ + nonDivisors := len(A) - divisors + result = append(result, nonDivisors) + nonDivisorsCountMap[val] = nonDivisors + } + } + return result +} + +/* +Task Score 77% +Correctness 100% +Performance 50% +*/ +func Solution1(A []int) []int { + result := []int{} + if len(A) < 0 { + return result + } + + elementDict := make(map[int]int) + for _, i := range A { + elementDict[i]++ + } + + for _, val := range A { + divisors := 0 + for factor := 1; factor <= int(math.Pow(float64(val), 0.5)); factor++ { + if val%factor == 0 { + // ๆชขๆŸฅๆ˜ฏๅฆๆœ‰ๅœจๅŽŸๅ…ˆ็š„ array ไธญ, ไธฆๅ–ๅพ—ๅ› ๅญๆฌกๆ•ธ + if v, ok := elementDict[factor]; ok { + divisors += v + } + + // ้ฟๅ…ๅ› ๅญ้‡่ค‡่จˆ็ฎ— + otherFactor := int(val / factor) + if v, ok := elementDict[otherFactor]; ok && otherFactor != factor { + divisors += v + } + } + } + // ๆŽจๅ‡บ้žๅ› ๅญๆฌกๆ•ธ + nonDivisors := len(A) - divisors + result = append(result, nonDivisors) + } + return result +} diff --git a/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible_test.go b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible_test.go new file mode 100644 index 000000000..729ac5740 --- /dev/null +++ b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible_test.go @@ -0,0 +1,40 @@ +package countnondivisible + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + want []int +}{ + { + []int{3, 1, 2, 3, 6}, + []int{2, 4, 3, 2, 0}, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolution2(t *testing.T) { + for _, tt := range tests { + if got := Solution2(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolution1(t *testing.T) { + for _, tt := range tests { + if got := Solution1(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/index.html b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/index.html new file mode 100644 index 000000000..06406d87a --- /dev/null +++ b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/index.html @@ -0,0 +1,3871 @@ + + + + + + + Count Non Divisible ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                +
                                                                                + + + + + + + + +
                                                                                + +
                                                                                + +
                                                                                + + + + + + + + +
                                                                                +
                                                                                + +
                                                                                +
                                                                                + +
                                                                                + +

                                                                                CountNonDivisible

                                                                                +

                                                                                Calculate the number of elements of an array that are not divisors(因數) of each element.

                                                                                +

                                                                                You are given an array A consisting of N integers.

                                                                                +

                                                                                For each number A[i] such that 0 ≤ i < N, we want to count the number of elements of the array that are not the divisors of A[i]. We say that these elements are non-divisors.

                                                                                +

                                                                                For example, consider integer N = 5 and array A such that:

                                                                                +
                                                                                A[0] = 3
                                                                                +A[1] = 1
                                                                                +A[2] = 2
                                                                                +A[3] = 3
                                                                                +A[4] = 6
                                                                                +

                                                                                For the following elements:

                                                                                +

                                                                                A[0] = 3, the non-divisors are: 2, 6, +A[1] = 1, the non-divisors are: 3, 2, 3, 6, +A[2] = 2, the non-divisors are: 3, 3, 6, +A[3] = 3, the non-divisors are: 2, 6, +A[4] = 6, there aren't any non-divisors. +Write a function:

                                                                                +

                                                                                func Solution(A []int) []int

                                                                                +

                                                                                that, given an array A consisting of N integers, returns a sequence of integers representing the amount of non-divisors.

                                                                                +

                                                                                Result array should be returned as an array of integers.

                                                                                +

                                                                                For example, given:

                                                                                +
                                                                                A[0] = 3
                                                                                +A[1] = 1
                                                                                +A[2] = 2
                                                                                +A[3] = 3
                                                                                +A[4] = 6
                                                                                +

                                                                                the function should return [2, 4, 3, 2, 0], as explained above.

                                                                                +

                                                                                Write an efficient algorithm for the following assumptions:

                                                                                +

                                                                                N is an integer within the range [1..50,000]; +each element of array A is an integer within the range [1..2 * N].

                                                                                +

                                                                                Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                                +

                                                                                題目大意

                                                                                +

                                                                                算出array中所有元素的非因子數的個數

                                                                                +

                                                                                解題思路

                                                                                +

                                                                                先算數每個數字出現的次數存入map +遍歷A, 對於每個元素從1到sqrt(i)中找出因子,如果是因子,就去字典找出出現次數 +最後用總長度減去因子數就可得出非因子數, 並將結果存入map, 空間換取時間

                                                                                +

                                                                                factor <= int(math.Pow(float64(val), 0.5)) 改成 factor*factor <= val 可提高效能

                                                                                +

                                                                                來源

                                                                                + +

                                                                                解答

                                                                                +

                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible.go

                                                                                +
                                                                                package countnondivisible
                                                                                +
                                                                                +import (
                                                                                +    "math"
                                                                                +)
                                                                                +
                                                                                +/*
                                                                                +Task Score 100%
                                                                                +Correctness 100%
                                                                                +Performance 100%
                                                                                +*/
                                                                                +func Solution(A []int) []int {
                                                                                +    // write your code in Go 1.4
                                                                                +    result := []int{}
                                                                                +    if len(A) < 0 {
                                                                                +        return result
                                                                                +    }
                                                                                +
                                                                                +    elementDict := make(map[int]int)
                                                                                +    for _, i := range A {
                                                                                +        elementDict[i]++
                                                                                +    }
                                                                                +
                                                                                +    // 用 map存起非因子數的個數, 空間換取時間
                                                                                +    nonDivisorsCountMap := make(map[int]int)
                                                                                +    for _, val := range A {
                                                                                +        if v, ok := nonDivisorsCountMap[val]; ok {
                                                                                +            result = append(result, v)
                                                                                +        } else {
                                                                                +            divisors := 0
                                                                                +            for factor := 1; factor*factor 
                                                                                +
                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                + + +
                                                                                + +
                                                                                +
                                                                                +
                                                                                + +

                                                                                results matching ""

                                                                                +
                                                                                  + +
                                                                                  +
                                                                                  + +

                                                                                  No results matching ""

                                                                                  + +
                                                                                  +
                                                                                  +
                                                                                  + +
                                                                                  +
                                                                                  + +
                                                                                  + + + + + + + + + + +
                                                                                  + + +
                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.go b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.go new file mode 100644 index 000000000..523c9c0b6 --- /dev/null +++ b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.go @@ -0,0 +1,116 @@ +package countsemiprimes + +func Solution(N int, P []int, Q []int) []int { + semiPrime := []int{} + + // ๅŠ่ณชๆ•ธ:ๅ…ฉๅ€‹่ณชๆ•ธ็š„ไน˜็ฉๆ‰€ๅพ—็š„่‡ช็„ถๆ•ธๆˆ‘ๅ€‘็จฑไน‹็‚บๅŠ่ณชๆ•ธ. + // 4, 6, 9, 10, 14, 15, 21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95,106, ... + // ๅฎƒๅ€‘ๅŒ…ๅซ1ๅŠ่‡ชๅทฑๅœจๅ…งๅˆๅ…ฑๆœ‰3ๆˆ–4ๅ€‹ๅ› ๆ•ธ + for i := 1; i <= N; i++ { + factorCount := 0 + sign := 0 + for j := 1; j*j <= i; j++ { + if i%j == 0 { + factorCount++ + f := i / j + if f != j { + if f == j*j { + // 3ๅ€‹็›ธๅŒ: ex i=27, j=3, f=9 + sign = 1 + semiPrime = append(semiPrime, 0) + break + } else { + factorCount++ + } + } + } + if factorCount > 4 { + sign = 1 + semiPrime = append(semiPrime, 0) + break + } + } + if sign != 1 { + if factorCount >= 3 { + semiPrime = append(semiPrime, i) + } else { + semiPrime = append(semiPrime, 0) + } + } + } + // idx 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 + // semiPrime 0 0 0 4 0 6 0 0 9 10 0 0 0 14 15 0 0 0 0 0 21 22 0 0 25 26 + + // fmt.Println("semiPrime", semiPrime) + + // ็•ถๅ‰arrayๅ’Œๅ‰้ขไธ€ๅ…ฑๆœ‰ๅนพๅ€‹ๅŠ่ณชๆ•ธ + indexMap := make(map[int]int) + // ๅฆ‚ๆžœๆ˜ฏๅŠ่ณชๆ•ธๆทปๅŠ ๅˆฐ map + semiMap := make(map[int]struct{}) + count := 0 + + for i := 0; i < len(semiPrime); i++ { + if semiPrime[i] != 0 { + count++ + indexMap[semiPrime[i]] = count + semiMap[semiPrime[i]] = struct{}{} + } else { + indexMap[i+1] = count + } + } + // indexMap : map[1:0 2:0 3:0 4:1 5:1 6:2 7:2 8:2 9:3 10:4 11:4 12:4 13:4 14:5 15:6 16:6 17:6 18:6 19:6 20:6 21:7 22:8 23:8 24:8 25:9 26:10] + // semiMap : map[4:0 6:0 9:0 10:0 14:0 15:0 21:0 22:0 25:0 26:0] + // fmt.Println("indexMap : ", indexMap) + // fmt.Println("semiMap : ", semiMap) + + result := []int{} + for i := 0; i < len(P); i++ { + if _, ok := semiMap[P[i]]; ok { + result = append(result, indexMap[Q[i]]-indexMap[P[i]]+1) + } else { + result = append(result, indexMap[Q[i]]-indexMap[P[i]]) + } + } + return result +} + +// TODO: +func Solution2(N int, P []int, Q []int) []int { + prime := make([]int, N+1) + i := 2 + for i*i <= N { + if prime[i] == 0 { + k := i * i + for k <= N { + if prime[k] == 0 { + prime[k] = i + } + k = k + i + } + } + i++ + } + // fmt.Println("prime: ", prime) + + // ็•ถๅ‰ไธ€ๅ…ฑๆœ‰ๅนพๅ€‹ๅŠ่ณชๆ•ธ + semiprime := make([]int, N+1) + for i := 1; i < len(prime); i++ { + p := prime[i] + if p == 0 { + semiprime[i] = semiprime[i-1] + continue + } + if prime[i/p] == 0 { + semiprime[i] = semiprime[i-1] + 1 + } else { + semiprime[i] = semiprime[i-1] + } + } + // fmt.Println("semiprime: ", semiprime) + + result := make([]int, len(P)) + for i, p := range P { + result[i] = semiprime[Q[i]] - semiprime[p-1] + } + return result +} diff --git a/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.py b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.py new file mode 100644 index 000000000..405e96dac --- /dev/null +++ b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.py @@ -0,0 +1,64 @@ +# https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L11_Sieve%20of%20Eratosthenes/11.2%20CountSemiprimes.md +def solution(N, P, Q): + """ + ่ฟ”ๅ›ž็”ฑๆ•ฐ็ป„Pใ€Q็š„ๅ…ƒ็ด ็ป„ๆˆ็š„ๅŒบ้—ดๅ†…๏ผŒไธๅคงไบŽN็š„ๅŠ็ด ๆ•ฐ็š„ไธชๆ•ฐ, ๆ—ถ้—ดๅคๆ‚ๅบฆO(N * log(log(N)) + M) + :param N: ๅŠ็ด ๆ•ฐ็š„ๆœ€ๅคงๅ€ผ + :param P: ๆ•ฐ็ป„ + :param Q: ๆ•ฐ็ป„ + :return: ๆฏๆฌกๆŸฅ่ฏข,ๅพ—ๅˆฐ็š„ๅŠ็ด ๆ•ฐ็š„ไธชๆ•ฐ + """ + # ๅŠ็ด ๆ•ฐๅชๆœ‰3ๆˆ–4ไธชๅ› ๅญ๏ผŒๅนถไธ”ไธ่ƒฝๆ˜ฏ็ด ๆ•ฐ็š„็ซ‹ๆ–น๏ผŒไพ‹ๅฆ‚(1, 3, 9, 27)(1, 5, 25, 125)่ฟ™็งๆƒ…ๅ†ต + # ้ฆ–ๅ…ˆ่ฎก็ฎ—ๅ‡บไธๅคงไบŽN็š„ๅŠ็ด ๆ•ฐๅˆ—่กจ๏ผŒๆ˜ฏๅŠ็ด ๆ•ฐ็š„ไธบๅ…ถๅ€ผ๏ผŒไธๆ˜ฏ็š„ไธบ0 + semi_prime = [] + k =0 + for i in range(1, N + 1): + factor_count = 0 + sign = 0 + for j in range(1, int(i ** 0.5) + 1): + if i % j == 0: + factor_count += 1 + f = i / j + if f != j: + if f == j ** 2: + sign = 1 + semi_prime.append(0) + break + else: + factor_count += 1 + if factor_count > 4: + sign = 1 + semi_prime.append(0) + break + if sign != 1: + if factor_count >= 3: + semi_prime.append(i) + else: + semi_prime.append(0) + + index_dict = {} # ๅพ—ๅ‡บๅฝ“ๅ‰ๆ•ฐๅ€ผไปฅๅŠๅ‰้ขไธ€ๅ…ฑๆœ‰ๅ‡ ไธชๅŠ็ด ๆ•ฐ + semi_dict = {} # ๅฆ‚ๆžœๆ˜ฏๅŠ็ด ๆ•ฐ๏ผŒๅˆ™ๆทปๅŠ ๅˆฐๅญ—ๅ…ธไธญ + count = 0 + for index, value in enumerate(semi_prime): + if value != 0: + count += 1 + index_dict[value] = count + semi_dict[value] = 0 + else: + index_dict[index + 1] = count + # index_dict {1: 0, 2: 0, 3: 0, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2, 9: 3, 10: 4, 11: 4, 12: 4, 13: 4, 14: 5, 15: 6, 16: 6, 17: 6, 18: 6, 19: 6, 20: 6, 21: 7, 22: 8, 23: 8, 24: 8, 25: 9, 26: 10} + #semi_dict {4: 0, 6: 0, 9: 0, 10: 0, 14: 0, 15: 0, 21: 0, 22: 0, 25: 0, 26: 0} + print("index_dict",index_dict) + print("semi_dict",semi_dict) + + result_list = [] # ๅผ€ๅง‹่ฎก็ฎ—๏ผŒๅœจๆŒ‡ๅฎšๅŒบ้—ดๅ†…ๆœ‰ๅ‡ ไธชๅŠ็ด ๆ•ฐ + for i, j in zip(P, Q): + if i in semi_dict: + result_list.append(index_dict[j] - index_dict[i] + 1) + else: + result_list.append(index_dict[j] - index_dict[i]) + + return result_list + + +if __name__ == '__main__': + solution(26,[1, 4, 16],[26, 10, 20]) \ No newline at end of file diff --git a/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes_test.go b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes_test.go new file mode 100644 index 000000000..be9116c64 --- /dev/null +++ b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes_test.go @@ -0,0 +1,62 @@ +package countsemiprimes + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 int + arg2 []int + arg3 []int + want []int +}{ + { + 26, + []int{1, 4, 16}, + []int{26, 10, 20}, + []int{10, 4, 0}, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2, tt.arg3); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolution2(t *testing.T) { + for _, tt := range tests { + if got := Solution2(tt.arg1, tt.arg2, tt.arg3); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSolution(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Solution(tests[0].arg1, tests[0].arg2, tests[0].arg3) + } +} + +func BenchmarkSolution2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Solution(tests[0].arg1, tests[0].arg2, tests[0].arg3) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkSolution-8 316700 3294 ns/op 1907 B/op 15 allocs/op +BenchmarkSolution2-8 361731 3326 ns/op 1906 B/op 15 allocs/op +PASS +ok LeetcodeGolang/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes 2.577s +*/ diff --git a/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/index.html b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/index.html new file mode 100644 index 000000000..7cfb88132 --- /dev/null +++ b/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/index.html @@ -0,0 +1,3901 @@ + + + + + + + Count Semiprimes ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                  +
                                                                                  + + + + + + + + +
                                                                                  + +
                                                                                  + +
                                                                                  + + + + + + + + +
                                                                                  +
                                                                                  + +
                                                                                  +
                                                                                  + +
                                                                                  + +

                                                                                  CountSemiprimes

                                                                                  +

                                                                                  Count the semiprime(半質數:兩個質數的乘積所得的自然數我們稱之為半質數) numbers in the given range [a..b]

                                                                                  +

                                                                                  A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.

                                                                                  +

                                                                                  A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26.

                                                                                  +

                                                                                  You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges.

                                                                                  +

                                                                                  Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 ≤ P[K] ≤ Q[K] ≤ N.

                                                                                  +

                                                                                  For example, consider an integer N = 26 and arrays P, Q such that:

                                                                                  +
                                                                                  P[0] = 1    Q[0] = 26
                                                                                  +P[1] = 4    Q[1] = 10
                                                                                  +P[2] = 16   Q[2] = 20
                                                                                  +

                                                                                  The number of semiprimes within each of these ranges is as follows:

                                                                                  +

                                                                                  (1, 26) is 10, +(4, 10) is 4, +(16, 20) is 0. +Write a function:

                                                                                  +

                                                                                  func Solution(N int, P []int, Q []int) []int

                                                                                  +

                                                                                  that, given an integer N and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries.

                                                                                  +

                                                                                  For example, given an integer N = 26 and arrays P, Q such that:

                                                                                  +
                                                                                  P[0] = 1    Q[0] = 26
                                                                                  +P[1] = 4    Q[1] = 10
                                                                                  +P[2] = 16   Q[2] = 20
                                                                                  +

                                                                                  the function should return the values [10, 4, 0], as explained above.

                                                                                  +

                                                                                  Write an efficient algorithm for the following assumptions:

                                                                                  +

                                                                                  N is an integer within the range [1..50,000]; +M is an integer within the range [1..30,000]; +each element of arrays P, Q is an integer within the range [1..N]; +P[i] ≤ Q[i]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                                  +

                                                                                  題目大意

                                                                                  +

                                                                                  計算[a,b]區間得半質數的個數

                                                                                  +

                                                                                  解題思路

                                                                                  +

                                                                                  先把半質數列表找出來. +(半質數:兩個質數的乘積所得的自然數我們稱之為半質數ㄝ開始的幾個半質數是4, 6, 9, 10, 14, 15, 21, 22, 25, 26, ... (OEIS中的數列A001358)它們包含1及自己在內合共有3或4個因數) +計算當前array和前面一共有幾個半質數 +遍歷P arry 算出 Q跟P 之前的半質數總和差, 並寫入結果

                                                                                  +

                                                                                  來源

                                                                                  + +

                                                                                  解答

                                                                                  +

                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.go

                                                                                  +
                                                                                  package countsemiprimes
                                                                                  +
                                                                                  +func Solution(N int, P []int, Q []int) []int {
                                                                                  +    semiPrime := []int{}
                                                                                  +
                                                                                  +    // 半質數:兩個質數的乘積所得的自然數我們稱之為半質數.
                                                                                  +    // 4, 6, 9, 10, 14, 15, 21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95,106, ...
                                                                                  +    // 它們包含1及自己在內合共有3或4個因數
                                                                                  +    for i := 1; i <= 0="" n;="" i++="" {="" factorcount="" :="0" sign="" for="" j="" j*j="" <="i;" j++="" if="" i%j="=" factorcount++="" f="" !="j" 3ๅ€‹็›ธๅŒ:="" ex="" i="27," semiprime="append(semiPrime," 0)="" break="" }="" else=""> 4 {
                                                                                  +                sign = 1
                                                                                  +                semiPrime = append(semiPrime, 0)
                                                                                  +                break
                                                                                  +            }
                                                                                  +        }
                                                                                  +        if sign != 1 {
                                                                                  +            if factorCount >= 3 {
                                                                                  +                semiPrime = append(semiPrime, i)
                                                                                  +            } else {
                                                                                  +                semiPrime = append(semiPrime, 0)
                                                                                  +            }
                                                                                  +        }
                                                                                  +    }
                                                                                  +    // idx         0 1 2 3 4 5 6 7 8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
                                                                                  +    // semiPrime 0 0 0 4 0 6 0 0 9 10  0  0  0 14 15  0  0  0  0  0 21 22  0  0 25 26
                                                                                  +
                                                                                  +    // fmt.Println("semiPrime", semiPrime)
                                                                                  +
                                                                                  +    // 當前array和前面一共有幾個半質數
                                                                                  +    indexMap := make(map[int]int)
                                                                                  +    // 如果是半質數添加到 map
                                                                                  +    semiMap := make(map[int]struct{})
                                                                                  +    count := 0
                                                                                  +
                                                                                  +    for i := 0; i < len(semiPrime); i++ {
                                                                                  +        if semiPrime[i] != 0 {
                                                                                  +            count++
                                                                                  +            indexMap[semiPrime[i]] = count
                                                                                  +            semiMap[semiPrime[i]] = struct{}{}
                                                                                  +        } else {
                                                                                  +            indexMap[i+1] = count
                                                                                  +        }
                                                                                  +    }
                                                                                  +    //     indexMap :  map[1:0 2:0 3:0 4:1 5:1 6:2 7:2 8:2 9:3 10:4 11:4 12:4 13:4 14:5 15:6 16:6 17:6 18:6 19:6 20:6 21:7 22:8 23:8 24:8 25:9 26:10]
                                                                                  +    // semiMap :  map[4:0 6:0 9:0 10:0 14:0 15:0 21:0 22:0 25:0 26:0]
                                                                                  +    // fmt.Println("indexMap : ", indexMap)
                                                                                  +    // fmt.Println("semiMap : ", semiMap)
                                                                                  +
                                                                                  +    result := []int{}
                                                                                  +    for i := 0; i < len(P); i++ {
                                                                                  +        if _, ok := semiMap[P[i]]; ok {
                                                                                  +            result = append(result, indexMap[Q[i]]-indexMap[P[i]]+1)
                                                                                  +        } else {
                                                                                  +            result = append(result, indexMap[Q[i]]-indexMap[P[i]])
                                                                                  +        }
                                                                                  +    }
                                                                                  +    return result
                                                                                  +}
                                                                                  +
                                                                                  +// TODO:
                                                                                  +func Solution2(N int, P []int, Q []int) []int {
                                                                                  +    prime := make([]int, N+1)
                                                                                  +    i := 2
                                                                                  +    for i*i 
                                                                                  +
                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                  + + +
                                                                                  + +
                                                                                  +
                                                                                  +
                                                                                  + +

                                                                                  results matching ""

                                                                                  +
                                                                                    + +
                                                                                    +
                                                                                    + +

                                                                                    No results matching ""

                                                                                    + +
                                                                                    +
                                                                                    +
                                                                                    + +
                                                                                    +
                                                                                    + +
                                                                                    + + + + + + + + + + +
                                                                                    + + +
                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers.go b/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers.go new file mode 100644 index 000000000..1cb714e24 --- /dev/null +++ b/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers.go @@ -0,0 +1,48 @@ +package chocolatesbynumbers + +func gcd(N int, M int) int { + if N%M == 0 { + return M + } else { + return gcd(M, N%M) + } +} + +/* +ๅฏไปฅๅƒๅˆฐ็š„ๅทงๅ…‹ๅŠ›็š„ๆ•ธ้‡ๅฐฑๆ˜ฏ็ธฝ็š„ๅทงๅ…‹ๅŠ›้ก†ๆ•ธ N ้™คไปฅ N ๅ’Œ M ็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธ +่จˆ็ฎ— Nๅ’ŒM็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธP, N้™คไปฅPๅพ—ๅˆฐๅ•†ๅณ็‚บ็ญ”ๆกˆ +O(log(N + M)) +*/ +func Solution(N int, M int) int { + return N / gcd(N, M) +} + +/* +Task Score 75% +Correctness 100% +Performance 50% +input (947853, 4453) the solution exceeded the time limit. +ๅพž0่™Ÿ้–‹ๅง‹ๅƒ, ไธ‹ไธ€ๅ€‹่™Ÿ็ขผ+M-1่™Ÿ +*/ +func SolutionBurst(N int, M int) int { + eaten := make(map[int]struct{}) + eatCount := 0 + + if N == 1 || M == 1 { + return N + } + + for { + sumNum := eatCount * M + startNum := sumNum % N + + if _, ok := eaten[startNum]; !ok { + eaten[startNum] = struct{}{} + eatCount++ + } else { + // ๆ‰พๅˆฐๅทฒๅƒ้Ž็š„ๅทงๅ…‹ๅŠ› + break + } + } + return eatCount +} diff --git a/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers_test.go b/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers_test.go new file mode 100644 index 000000000..7b253ba30 --- /dev/null +++ b/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers_test.go @@ -0,0 +1,66 @@ +package chocolatesbynumbers + +import "testing" + +var tests = []struct { + arg1 int + arg2 int + want int +}{ + { + 10, + 4, + 5, + }, + { + 947853, + 4453, + 947853, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSolutionBurst(t *testing.T) { + for _, tt := range tests { + if got := SolutionBurst(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSolution(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + for _, tt := range tests { + Solution(tt.arg1, tt.arg2) + } + } +} + +func BenchmarkSolutionBurst(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + for _, tt := range tests { + SolutionBurst(tt.arg1, tt.arg2) + } + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkSolution-4 12411740 112.2 ns/op 0 B/op 0 allocs/op +BenchmarkSolutionBurst-4 3 354775339 ns/op 49782528 B/op 38396 allocs/op +PASS +ok LeetcodeGolang/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers 4.425s +*/ diff --git a/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/index.html b/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/index.html new file mode 100644 index 000000000..1f8cb6eaa --- /dev/null +++ b/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/index.html @@ -0,0 +1,3870 @@ + + + + + + + Chocolates By Numbers ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                    +
                                                                                    + + + + + + + + +
                                                                                    + +
                                                                                    + +
                                                                                    + + + + + + + + +
                                                                                    +
                                                                                    + +
                                                                                    +
                                                                                    + +
                                                                                    + +

                                                                                    ChocolatesByNumbers

                                                                                    +

                                                                                    There are N chocolates in a circle. Count the number of chocolates you will eat.

                                                                                    +

                                                                                    Two positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N − 1.

                                                                                    +

                                                                                    You start to eat the chocolates. After eating a chocolate you leave only a wrapper.

                                                                                    +

                                                                                    You begin with eating chocolate number 0. Then you omit(忽略) the next M − 1 chocolates or wrappers on the circle, and eat the following one.

                                                                                    +

                                                                                    More precisely(恰恰), if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division).

                                                                                    +

                                                                                    You stop eating when you encounter an empty wrapper.

                                                                                    +

                                                                                    For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6.

                                                                                    +

                                                                                    The goal is to count the number of chocolates that you will eat, following the above rules.

                                                                                    +

                                                                                    Write a function:

                                                                                    +

                                                                                    func Solution(N int, M int) int

                                                                                    +

                                                                                    that, given two positive integers N and M, returns the number of chocolates that you will eat.

                                                                                    +

                                                                                    For example, given integers N = 10 and M = 4. the function should return 5, as explained above.

                                                                                    +

                                                                                    Write an efficient algorithm for the following assumptions:

                                                                                    +

                                                                                    N and M are integers within the range [1..1,000,000,000].

                                                                                    +

                                                                                    Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                                    +

                                                                                    題目大意

                                                                                    +

                                                                                    N塊巧克力,如果吃的是X號 下一個是吃 (X + M) modulo N 號 +總共可以吃幾顆.

                                                                                    +

                                                                                    解題思路

                                                                                    +

                                                                                    方法ㄧ: 從0號開始吃, 下一個號碼+M-1號. 迴圈去跑 +方法二: 可以吃到的巧克力的數量就是總的巧克力顆數 N 除以 N 和 M 的最大公因數. 計算 N和M的最大公因數P, N除以P得到商即為答案

                                                                                    +

                                                                                    來源

                                                                                    +

                                                                                    https://app.codility.com/programmers/lessons/12-euclidean_algorithm/chocolates_by_numbers/

                                                                                    +

                                                                                    解答

                                                                                    +

                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers.go

                                                                                    +
                                                                                    package chocolatesbynumbers
                                                                                    +
                                                                                    +func gcd(N int, M int) int {
                                                                                    +    if N%M == 0 {
                                                                                    +        return M
                                                                                    +    } else {
                                                                                    +        return gcd(M, N%M)
                                                                                    +    }
                                                                                    +}
                                                                                    +
                                                                                    +/*
                                                                                    +可以吃到的巧克力的數量就是總的巧克力顆數 N 除以 N 和 M 的最大公因數
                                                                                    +計算 N和M的最大公因數P, N除以P得到商即為答案
                                                                                    +O(log(N + M))
                                                                                    +*/
                                                                                    +func Solution(N int, M int) int {
                                                                                    +    return N / gcd(N, M)
                                                                                    +}
                                                                                    +
                                                                                    +/*
                                                                                    +Task Score 75%
                                                                                    +Correctness 100%
                                                                                    +Performance 50%
                                                                                    +input (947853, 4453) the solution exceeded the time limit.
                                                                                    +從0號開始吃, 下一個號碼+M-1號
                                                                                    +*/
                                                                                    +func SolutionBurst(N int, M int) int {
                                                                                    +    eaten := make(map[int]struct{})
                                                                                    +    eatCount := 0
                                                                                    +
                                                                                    +    if N == 1 || M == 1 {
                                                                                    +        return N
                                                                                    +    }
                                                                                    +
                                                                                    +    for {
                                                                                    +        sumNum := eatCount * M
                                                                                    +        startNum := sumNum % N
                                                                                    +
                                                                                    +        if _, ok := eaten[startNum]; !ok {
                                                                                    +            eaten[startNum] = struct{}{}
                                                                                    +            eatCount++
                                                                                    +        } else {
                                                                                    +            // 找到已吃過的巧克力
                                                                                    +            break
                                                                                    +        }
                                                                                    +    }
                                                                                    +    return eatCount
                                                                                    +}
                                                                                    +
                                                                                    +
                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                    + + +
                                                                                    + +
                                                                                    +
                                                                                    +
                                                                                    + +

                                                                                    results matching ""

                                                                                    +
                                                                                      + +
                                                                                      +
                                                                                      + +

                                                                                      No results matching ""

                                                                                      + +
                                                                                      +
                                                                                      +
                                                                                      + +
                                                                                      +
                                                                                      + +
                                                                                      + + + + + + + + + + +
                                                                                      + + +
                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors.go b/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors.go new file mode 100644 index 000000000..0c004f50d --- /dev/null +++ b/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors.go @@ -0,0 +1,51 @@ +package commonprimedivisors + +/* +func gcd(a, b int) int { + for b != 0 { + t := b + b = a % b + a = t + } + return a +} +*/ +func gcd(N int, M int) int { + if N%M == 0 { + return M + } else { + return gcd(M, N%M) + } +} + +func Solution(A []int, B []int) int { + result := 0 + for i := 0; i < len(A); i++ { + if A[i] == B[i] { + result++ + continue + } + // ๅ…ˆๅˆคๆ–ทๅ…ฉๆ•ธ็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธ, + abGcd := gcd(A[i], B[i]) + + // ๅ†ๅˆคๆ–ทๅ…ฉๅ€‹ๆ•ธๆ˜ฏๅซๆœ‰ๆœ€ๅคงๅ…ฌๅ› ๆ•ธๆฒ’ๆœ‰็š„ๅ› ๅญ + a := A[i] / abGcd + aGcd := gcd(a, abGcd) + for aGcd != 1 { + // ้‚„ๆœ‰ๅ…ถไป–ๅ› ๅญ + a = a / aGcd + aGcd = gcd(aGcd, a) + } + + b := B[i] / abGcd + bGcd := gcd(b, abGcd) + for bGcd != 1 { + b = b / bGcd + bGcd = gcd(bGcd, b) + } + if a == b { + result++ + } + } + return result +} diff --git a/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors_test.go b/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors_test.go new file mode 100644 index 000000000..77909f3ec --- /dev/null +++ b/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors_test.go @@ -0,0 +1,23 @@ +package commonprimedivisors + +import "testing" + +var tests = []struct { + arg1 []int + arg2 []int + want int +}{ + { + []int{15, 10, 3}, + []int{75, 30, 5}, + 1, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/index.html b/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/index.html new file mode 100644 index 000000000..0dc0a0ab5 --- /dev/null +++ b/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/index.html @@ -0,0 +1,3883 @@ + + + + + + + Common Prime Divisors ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                      +
                                                                                      + + + + + + + + +
                                                                                      + +
                                                                                      + +
                                                                                      + + + + + + + + +
                                                                                      +
                                                                                      + +
                                                                                      +
                                                                                      + +
                                                                                      + +

                                                                                      CommonPrimeDivisors

                                                                                      +

                                                                                      Check whether two numbers have the same prime divisors.

                                                                                      +

                                                                                      A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13.

                                                                                      +

                                                                                      A prime D is called a prime divisor(質因數) of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20.

                                                                                      +

                                                                                      You are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same.

                                                                                      +

                                                                                      For example, given:

                                                                                      +

                                                                                      N = 15 and M = 75, the prime divisors are the same: {3, 5}; +N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5}; +N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}. +Write a function:

                                                                                      +

                                                                                      func Solution(A []int, B []int) int

                                                                                      +

                                                                                      that, given two non-empty arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same.

                                                                                      +

                                                                                      For example, given:

                                                                                      +
                                                                                      A[0] = 15   B[0] = 75
                                                                                      +A[1] = 10   B[1] = 30
                                                                                      +A[2] = 3    B[2] = 5
                                                                                      +

                                                                                      the function should return 1, because only one pair (15, 75) has the same set of prime divisors.

                                                                                      +

                                                                                      Write an efficient algorithm for the following assumptions:

                                                                                      +

                                                                                      Z is an integer within the range [1..6,000]; +each element of arrays A, B is an integer within the range [1..2,147,483,647]. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                                      +

                                                                                      題目大意

                                                                                      +

                                                                                      判斷兩個數是否有相同的質因數

                                                                                      +

                                                                                      解題思路

                                                                                      +

                                                                                      先判斷兩數的最大公因數, 再判斷兩個數是含有最大公因數沒有的因子 +15 , 75 的最大公因數為 35 +15= 35 +75= 355

                                                                                      +

                                                                                      來源

                                                                                      + +

                                                                                      解答

                                                                                      +

                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors.go

                                                                                      +
                                                                                      package commonprimedivisors
                                                                                      +
                                                                                      +/*
                                                                                      +func gcd(a, b int) int {
                                                                                      +    for b != 0 {
                                                                                      +        t := b
                                                                                      +        b = a % b
                                                                                      +        a = t
                                                                                      +    }
                                                                                      +    return a
                                                                                      +}
                                                                                      +*/
                                                                                      +func gcd(N int, M int) int {
                                                                                      +    if N%M == 0 {
                                                                                      +        return M
                                                                                      +    } else {
                                                                                      +        return gcd(M, N%M)
                                                                                      +    }
                                                                                      +}
                                                                                      +
                                                                                      +func Solution(A []int, B []int) int {
                                                                                      +    result := 0
                                                                                      +    for i := 0; i < len(A); i++ {
                                                                                      +        if A[i] == B[i] {
                                                                                      +            result++
                                                                                      +            continue
                                                                                      +        }
                                                                                      +        // 先判斷兩數的最大公因數,
                                                                                      +        abGcd := gcd(A[i], B[i])
                                                                                      +
                                                                                      +        // 再判斷兩個數是含有最大公因數沒有的因子
                                                                                      +        a := A[i] / abGcd
                                                                                      +        aGcd := gcd(a, abGcd)
                                                                                      +        for aGcd != 1 {
                                                                                      +            // 還有其他因子
                                                                                      +            a = a / aGcd
                                                                                      +            aGcd = gcd(aGcd, a)
                                                                                      +        }
                                                                                      +
                                                                                      +        b := B[i] / abGcd
                                                                                      +        bGcd := gcd(b, abGcd)
                                                                                      +        for bGcd != 1 {
                                                                                      +            b = b / bGcd
                                                                                      +            bGcd = gcd(bGcd, b)
                                                                                      +        }
                                                                                      +        if a == b {
                                                                                      +            result++
                                                                                      +        }
                                                                                      +    }
                                                                                      +    return result
                                                                                      +}
                                                                                      +
                                                                                      +
                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                      + + +
                                                                                      + +
                                                                                      +
                                                                                      +
                                                                                      + +

                                                                                      results matching ""

                                                                                      +
                                                                                        + +
                                                                                        +
                                                                                        + +

                                                                                        No results matching ""

                                                                                        + +
                                                                                        +
                                                                                        +
                                                                                        + +
                                                                                        +
                                                                                        + +
                                                                                        + + + + + + + + + + +
                                                                                        + + +
                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog.go b/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog.go new file mode 100644 index 000000000..d6034c054 --- /dev/null +++ b/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog.go @@ -0,0 +1,82 @@ +package fibfrog + +/** + * @description: ็”ข็”Ÿไธๅคงๆ–ผn็š„ๆ–ๆณข้‚ฃๅฅ‘ๆ•ธ็š„ๅˆ—่กจ + * @param {int} N + * @return {*} + */ +func Fib(N int) (fibArr []int) { + fibArr = append(fibArr, 0) + fibArr = append(fibArr, 1) + fibArr = append(fibArr, 1) + i := 2 + for fibArr[i] < N { + i = i + 1 + fibArr = append(fibArr, fibArr[i-1]+fibArr[i-2]) + } + return fibArr +} + +func Solution(A []int) int { + // ็ต‚้ปž + A = append(A, 1) + N := len(A) + fibArr := Fib(N) + // ไธ€ๆฌกๅฐฑๅฏไปฅๅพž -1 ่ทณๅˆฐ N + if fibArr[len(fibArr)-1] == N { + return 1 + } + fibArr = fibArr[1 : len(fibArr)-1] + // fmt.Println(fibArr) + + // get the leafs that can be reached from the starting shore + reachable := make([]int, N) + for _, v := range fibArr { + if A[v-1] == 1 { + // ๆ‰พๅˆฐๆจน่‘‰ + reachable[v-1] = 1 + } + } + // ไธ€้–‹ๅง‹ๅช่ƒฝ่ทณๅˆฐ index: 4 , fibๆ˜ฏ [1 1 2 3 5 8], ๆœƒไฝฟ็”จๅˆฐ 5 + // fmt.Println("re", reachable) // [0 0 0 0 1 0 0 0 0 0 0 0] + + // iterate all the positions until you reach the other shore + for i := 0; i < N; i++ { + // ๅฟฝ็•ฅไธๆ˜ฏ่‘‰ๅญๆˆ–ๅทฒ็ถ“ๆ‰พ้Ž็š„path + if A[i] != 1 || reachable[i] > 0 { + continue + } + + // get the optimal jump count to reach this leaf + if A[i] == 1 { + // ๆœ‰ๆจน่‘‰ + // ้ๆญทๆ–ๆณข้‚ฃๅฅ‘ๆ•ธๅˆ—, ๅฐ‹ๆ‰พๆœ€ๅฐ‘็š„่ทณ่บๆฌกๆ•ธ + minJump := i + 1 + canJump := false + for _, f := range fibArr { + previousIdx := i - f + + if previousIdx < 0 || reachable[previousIdx] == 0 { + // fmt.Printf("[No] %d :previousIdx = %d reachable = %v \n", i, previousIdx, reachable) + continue + } + + if minJump > reachable[previousIdx] { + // ๆญค previousIdx ไฝ็ฝฎๅฏไปฅๅˆฐ้” + // fmt.Printf("%d :previousIdx = %d reachable = %v \n", i, previousIdx, reachable) + minJump = reachable[previousIdx] + canJump = true + } + } + if canJump { + reachable[i] = minJump + 1 + } + } + // fmt.Printf("i=%d , reachable = %v \n", i, reachable) + } + + if reachable[len(reachable)-1] == 0 { + return -1 + } + return reachable[len(reachable)-1] +} diff --git a/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog_test.go b/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog_test.go new file mode 100644 index 000000000..4d105d6c2 --- /dev/null +++ b/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog_test.go @@ -0,0 +1,21 @@ +package fibfrog + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0}, + 3, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/index.html b/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/index.html new file mode 100644 index 000000000..56ff3dec3 --- /dev/null +++ b/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/index.html @@ -0,0 +1,3930 @@ + + + + + + + Fib Frog ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                        +
                                                                                        + + + + + + + + +
                                                                                        + +
                                                                                        + +
                                                                                        + + + + + + + + +
                                                                                        +
                                                                                        + +
                                                                                        +
                                                                                        + +
                                                                                        + +

                                                                                        FibFrog

                                                                                        +

                                                                                        The Fibonacci sequence is defined using the following recursive formula:

                                                                                        +
                                                                                        F(0) = 0
                                                                                        +F(1) = 1
                                                                                        +F(M) = F(M - 1) + F(M - 2) if M >= 2
                                                                                        +

                                                                                        A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N.

                                                                                        +

                                                                                        The leaves on the river are represented in an array A consisting of N integers. Consecutive(連續的) elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s:

                                                                                        +

                                                                                        0 represents a position without a leaf; +1 represents a position containing a leaf. +The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf.

                                                                                        +

                                                                                        For example, consider array A such that:

                                                                                        +
                                                                                        A[0] = 0
                                                                                        +A[1] = 0
                                                                                        +A[2] = 0
                                                                                        +A[3] = 1
                                                                                        +A[4] = 1
                                                                                        +A[5] = 0
                                                                                        +A[6] = 1
                                                                                        +A[7] = 0
                                                                                        +A[8] = 0
                                                                                        +A[9] = 0
                                                                                        +A[10] = 0
                                                                                        +

                                                                                        The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5.

                                                                                        +

                                                                                        Write a function:

                                                                                        +

                                                                                        func Solution(A []int) int

                                                                                        +

                                                                                        that, given an array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1.

                                                                                        +

                                                                                        For example, given:

                                                                                        +
                                                                                        A[0] = 0
                                                                                        +A[1] = 0
                                                                                        +A[2] = 0
                                                                                        +A[3] = 1
                                                                                        +A[4] = 1
                                                                                        +A[5] = 0
                                                                                        +A[6] = 1
                                                                                        +A[7] = 0
                                                                                        +A[8] = 0
                                                                                        +A[9] = 0
                                                                                        +A[10] = 0
                                                                                        +

                                                                                        the function should return 3, as explained above.

                                                                                        +

                                                                                        Write an efficient algorithm for the following assumptions:

                                                                                        +

                                                                                        N is an integer within the range [0..100,000]; +each element of array A is an integer that can have one of the following values: 0, 1. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                                        +

                                                                                        題目大意

                                                                                        +

                                                                                        一只小青蛙想到對岸。它開始位於河的另一邊 位置-1, 想要到對面的河岸 位置N . 青蛙可以跳任意距離 F(K). 其中F(K)是第K個斐波那契數. +且河上有許多樹葉 A[0] = 0 代表位置 0 沒有樹葉, 1 代表有樹葉 +青蛙可以在樹葉之間跳, 但只能朝河岸 N 的方向跳 +找出最小跳的次數

                                                                                        +

                                                                                        解題思路

                                                                                        +

                                                                                        廣度優先搜尋 (Breadth-First Search, BFS) 問題. +對於河上有樹葉的位置index, 則遍歷比index小的斐波那契數f, +只要 index - f 這個位置可以達到, 這index的位置就可以經過一次跳躍長度為f

                                                                                        +

                                                                                        來源

                                                                                        + +

                                                                                        解答

                                                                                        +

                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog.go

                                                                                        +
                                                                                        package fibfrog
                                                                                        +
                                                                                        +/**
                                                                                        + * @description: 產生不大於n的斐波那契數的列表
                                                                                        + * @param {int} N
                                                                                        + * @return {*}
                                                                                        + */
                                                                                        +func Fib(N int) (fibArr []int) {
                                                                                        +    fibArr = append(fibArr, 0)
                                                                                        +    fibArr = append(fibArr, 1)
                                                                                        +    fibArr = append(fibArr, 1)
                                                                                        +    i := 2
                                                                                        +    for fibArr[i] < N {
                                                                                        +        i = i + 1
                                                                                        +        fibArr = append(fibArr, fibArr[i-1]+fibArr[i-2])
                                                                                        +    }
                                                                                        +    return fibArr
                                                                                        +}
                                                                                        +
                                                                                        +func Solution(A []int) int {
                                                                                        +    // 終點
                                                                                        +    A = append(A, 1)
                                                                                        +    N := len(A)
                                                                                        +    fibArr := Fib(N)
                                                                                        +    // 一次就可以從 -1 跳到 N
                                                                                        +    if fibArr[len(fibArr)-1] == N {
                                                                                        +        return 1
                                                                                        +    }
                                                                                        +    fibArr = fibArr[1 : len(fibArr)-1]
                                                                                        +    // fmt.Println(fibArr)
                                                                                        +
                                                                                        +    // get the leafs that can be reached from the starting shore
                                                                                        +    reachable := make([]int, N)
                                                                                        +    for _, v := range fibArr {
                                                                                        +        if A[v-1] == 1 {
                                                                                        +            // 找到樹葉
                                                                                        +            reachable[v-1] = 1
                                                                                        +        }
                                                                                        +    }
                                                                                        +    // 一開始只能跳到 index: 4 , fib是 [1 1 2 3 5 8], 會使用到 5
                                                                                        +    // fmt.Println("re", reachable) // [0 0 0 0 1 0 0 0 0 0 0 0]
                                                                                        +
                                                                                        +    // iterate all the positions until you reach the other shore
                                                                                        +    for i := 0; i < N; i++ {
                                                                                        +        // 忽略不是葉子或已經找過的path
                                                                                        +        if A[i] != 1 || reachable[i] > 0 {
                                                                                        +            continue
                                                                                        +        }
                                                                                        +
                                                                                        +        // get the optimal jump count to reach this leaf
                                                                                        +        if A[i] == 1 {
                                                                                        +            // 有樹葉
                                                                                        +            // 遍歷斐波那契數列, 尋找最少的跳躍次數
                                                                                        +            minJump := i + 1
                                                                                        +            canJump := false
                                                                                        +            for _, f := range fibArr {
                                                                                        +                previousIdx := i - f
                                                                                        +
                                                                                        +                if previousIdx < 0 || reachable[previousIdx] == 0 {
                                                                                        +                    // fmt.Printf("[No] %d :previousIdx = %d reachable = %v \n", i, previousIdx, reachable)
                                                                                        +                    continue
                                                                                        +                }
                                                                                        +
                                                                                        +                if minJump > reachable[previousIdx] {
                                                                                        +                    // 此 previousIdx 位置可以到達
                                                                                        +                    // fmt.Printf("%d :previousIdx = %d reachable = %v \n", i, previousIdx, reachable)
                                                                                        +                    minJump = reachable[previousIdx]
                                                                                        +                    canJump = true
                                                                                        +                }
                                                                                        +            }
                                                                                        +            if canJump {
                                                                                        +                reachable[i] = minJump + 1
                                                                                        +            }
                                                                                        +        }
                                                                                        +        // fmt.Printf("i=%d , reachable = %v \n", i, reachable)
                                                                                        +    }
                                                                                        +
                                                                                        +    if reachable[len(reachable)-1] == 0 {
                                                                                        +        return -1
                                                                                        +    }
                                                                                        +    return reachable[len(reachable)-1]
                                                                                        +}
                                                                                        +
                                                                                        +
                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                        + + +
                                                                                        + +
                                                                                        +
                                                                                        +
                                                                                        + +

                                                                                        results matching ""

                                                                                        +
                                                                                          + +
                                                                                          +
                                                                                          + +

                                                                                          No results matching ""

                                                                                          + +
                                                                                          +
                                                                                          +
                                                                                          + +
                                                                                          +
                                                                                          + +
                                                                                          + + + + + + +
                                                                                          + + +
                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct.go b/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct.go new file mode 100644 index 000000000..64fefc60a --- /dev/null +++ b/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct.go @@ -0,0 +1,8 @@ +package absdistinct + +func Solution(A []int) int { + if len(A) <= 0 { + return 0 + } + return 0 +} diff --git a/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct_test.go b/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct_test.go new file mode 100644 index 000000000..640b19bc1 --- /dev/null +++ b/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct_test.go @@ -0,0 +1,21 @@ +package absdistinct + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{-5, -3, -1, 0, 3, 6}, + 5, + }, +} + +func TestSolution(t *testing.T) { + for _, tt := range tests { + if got := Solution(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/index.html b/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/index.html new file mode 100644 index 000000000..db1eb2fe5 --- /dev/null +++ b/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/index.html @@ -0,0 +1,3842 @@ + + + + + + + Abs Distinct ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                          +
                                                                                          + + + + + + + + +
                                                                                          + +
                                                                                          + +
                                                                                          + + + + + + + + +
                                                                                          +
                                                                                          + +
                                                                                          +
                                                                                          + +
                                                                                          + +

                                                                                          AbsDistinct

                                                                                          +

                                                                                          A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array.

                                                                                          +

                                                                                          For example, consider array A such that:

                                                                                          +

                                                                                          A[0] = -5 + A[1] = -3 + A[2] = -1 + A[3] = 0 + A[4] = 3 + A[5] = 6 +The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6.

                                                                                          +

                                                                                          Write a function:

                                                                                          +

                                                                                          func Solution(A []int) int

                                                                                          +

                                                                                          that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A.

                                                                                          +

                                                                                          For example, given array A such that:

                                                                                          +

                                                                                          A[0] = -5 + A[1] = -3 + A[2] = -1 + A[3] = 0 + A[4] = 3 + A[5] = 6 +the function should return 5, as explained above.

                                                                                          +

                                                                                          Write an efficient algorithm for the following assumptions:

                                                                                          +

                                                                                          N is an integer within the range [1..100,000]; +each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]; +array A is sorted in non-decreasing order. +Copyright 2009–2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

                                                                                          +

                                                                                          "有序數組中絕對值不同的數的個數"指的是,一個已經排好序的整數數組中絕對值不相同的數字的個數,

                                                                                          +

                                                                                          例如:

                                                                                          +

                                                                                          A[0] = -5 A[1] = -3 A[2] = -1 +A[3] = 0 A[4] = 3 A[5] = 6 +絕對值不同的數的個數為 5, 因為其中有 5 個不同的絕對值: 0, 1, 3, 5, 6

                                                                                          +

                                                                                          編寫一個函數:

                                                                                          +

                                                                                          func Solution(A []int) int

                                                                                          +

                                                                                          請返回給定有序數組中絕對值不同的數的個數。

                                                                                          +

                                                                                          例如,給出數組A:

                                                                                          +

                                                                                          A[0] = -5 A[1] = -3 A[2] = -1 +A[3] = 0 A[4] = 3 A[5] = 6 +函數應返回5。

                                                                                          +

                                                                                          假定:

                                                                                          +

                                                                                          N 是 [1..100,000] 內的 整數; +數組 A 每個元素是取值範圍 [−2,147,483,648..2,147,483,647] 內的 整數 ; +數組 A 是 非-遞增 序列.

                                                                                          +

                                                                                          題目大意

                                                                                          +

                                                                                          解題思路

                                                                                          +

                                                                                          來源

                                                                                          + +

                                                                                          解答

                                                                                          +

                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct.go

                                                                                          +
                                                                                          
                                                                                          +
                                                                                          +
                                                                                          +
                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                          + + +
                                                                                          + +
                                                                                          +
                                                                                          +
                                                                                          + +

                                                                                          results matching ""

                                                                                          +
                                                                                            + +
                                                                                            +
                                                                                            + +

                                                                                            No results matching ""

                                                                                            + +
                                                                                            +
                                                                                            +
                                                                                            + +
                                                                                            +
                                                                                            + +
                                                                                            + + + + + + +
                                                                                            + + +
                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Content.html b/Content.html new file mode 100644 index 000000000..02b3f7794 --- /dev/null +++ b/Content.html @@ -0,0 +1,4215 @@ + + + + + + + Content ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                            +
                                                                                            + + + + + + + + +
                                                                                            + +
                                                                                            + +
                                                                                            + + + + + + + + +
                                                                                            +
                                                                                            + +
                                                                                            +
                                                                                            + +
                                                                                            + +

                                                                                            Kimi's LeetcodeGolang Notes

                                                                                            + +
                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:14:52
                                                                                            + + +
                                                                                            + +
                                                                                            +
                                                                                            +
                                                                                            + +

                                                                                            results matching ""

                                                                                            +
                                                                                              + +
                                                                                              +
                                                                                              + +

                                                                                              No results matching ""

                                                                                              + +
                                                                                              +
                                                                                              +
                                                                                              + +
                                                                                              +
                                                                                              + +
                                                                                              + + + + + + + + + + + + + + +
                                                                                              + + +
                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements.go b/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements.go new file mode 100644 index 000000000..561e82b01 --- /dev/null +++ b/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements.go @@ -0,0 +1,72 @@ +package findminimumdifferencebetweenanytwoelements + +import ( + "math" + "sort" +) + +/* +https://yourbasic.org/golang/absolute-value-int-float/ +http://cavaliercoder.com/blog/optimized-abs-for-int64-in-go.html +fmt.Println(abs(math.MinInt64)) // Output: -9223372036854775808 + +// ไผผไนŽๆฏ”่ผƒๅฟซ +func WithTwosComplement(n int64) int64 { + y := n >> 63 // y โ† x โŸซ 63 + return (n ^ y) - y // (x โจ y) - y +} +*/ +func abs(n int) int { + if n < 0 { + return -n + } + return n +} + +func WithTwosComplement(n int64) int64 { + y := n >> 63 // y โ† x โŸซ 63 + return (n ^ y) - y // (x โจ y) - y +} + +// O(n Log n) +func FindMinDiff(nums []int) int { + if len(nums) <= 0 { + return 0 + } + sort.Ints(nums) // O(n Log n) + + minSize := math.MaxInt32 + + // O(n) + for i := 1; i < len(nums); i++ { + tmp := int(math.Abs(float64(nums[i] - nums[i-1]))) + if minSize > tmp { + minSize = tmp + } + } + + if minSize == math.MaxInt32 { + minSize = 0 + } + return minSize +} + +func FindMinDiff2(nums []int) int { + if len(nums) <= 0 { + return 0 + } + sort.Ints(nums) + + minSize := math.MaxInt32 + for i := 1; i < len(nums); i++ { + tmp := abs(nums[i] - nums[i-1]) + if minSize > tmp { + minSize = tmp + } + } + + if minSize == math.MaxInt32 { + minSize = 0 + } + return minSize +} diff --git a/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements_test.go b/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements_test.go new file mode 100644 index 000000000..182682634 --- /dev/null +++ b/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements_test.go @@ -0,0 +1,51 @@ +package findminimumdifferencebetweenanytwoelements + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{1, 5, 3, 19, 18, 25}, + 1, + }, + { + []int{30, 5, 20, 9}, + 4, + }, + { + []int{1, 19, -4, 31, 38, 25, 100}, + 5, + }, + { + []int{1}, + 0, + }, +} + +func TestFindMinDiff(t *testing.T) { + for _, tt := range tests { + if got := FindMinDiff(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkFindMinDiff(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FindMinDiff(tests[0].arg1) + } +} + +func BenchmarkFindMinDiff2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FindMinDiff(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements -bench=. +*/ diff --git a/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/index.html b/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/index.html new file mode 100644 index 000000000..394ebc9e5 --- /dev/null +++ b/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/index.html @@ -0,0 +1,3863 @@ + + + + + + + 0031.Find-Minimum-Difference-Between-Any-Two-Elements ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                              +
                                                                                              + + + + + + + + +
                                                                                              + +
                                                                                              + +
                                                                                              + + + + + + + + +
                                                                                              +
                                                                                              + +
                                                                                              +
                                                                                              + +
                                                                                              + +

                                                                                              0031. Find Minimum Difference Between Any Two Elements

                                                                                              +

                                                                                              題目

                                                                                              +

                                                                                              Given an unsorted array, find the minimum difference between any pair in given array. +Examples :

                                                                                              +

                                                                                              Input : {1, 5, 3, 19, 18, 25}; +Output : 1 +Minimum difference is between 18 and 19

                                                                                              +

                                                                                              Input : {30, 5, 20, 9}; +Output : 4 +Minimum difference is between 5 and 9

                                                                                              +

                                                                                              Input : {1, 19, -4, 31, 38, 25, 100}; +Output : 5 +Minimum difference is between 1 and -4

                                                                                              +

                                                                                              來源

                                                                                              + +

                                                                                              解答

                                                                                              +

                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements.go

                                                                                              +
                                                                                              package findminimumdifferencebetweenanytwoelements
                                                                                              +
                                                                                              +import (
                                                                                              +    "math"
                                                                                              +    "sort"
                                                                                              +)
                                                                                              +
                                                                                              +/*
                                                                                              +https://yourbasic.org/golang/absolute-value-int-float/
                                                                                              +http://cavaliercoder.com/blog/optimized-abs-for-int64-in-go.html
                                                                                              +fmt.Println(abs(math.MinInt64)) // Output: -9223372036854775808
                                                                                              +
                                                                                              +// 似乎比較快
                                                                                              +func WithTwosComplement(n int64) int64 {
                                                                                              +    y := n >> 63          // y ← x ⟫ 63
                                                                                              +    return (n ^ y) - y    // (x ⨁ y) - y
                                                                                              +}
                                                                                              +*/
                                                                                              +func abs(n int) int {
                                                                                              +    if n < 0 {
                                                                                              +        return -n
                                                                                              +    }
                                                                                              +    return n
                                                                                              +}
                                                                                              +
                                                                                              +func WithTwosComplement(n int64) int64 {
                                                                                              +    y := n >> 63       // y ← x ⟫ 63
                                                                                              +    return (n ^ y) - y // (x ⨁ y) - y
                                                                                              +}
                                                                                              +
                                                                                              +// O(n Log n)
                                                                                              +func FindMinDiff(nums []int) int {
                                                                                              +    if len(nums) <= 0="" {="" return="" }="" sort.ints(nums)="" o(n="" log="" n)="" minsize="" :="math.MaxInt32" o(n)="" for="" i="" <="" len(nums);="" i++="" tmp="" -="" nums[i-1])))="" if=""> tmp {
                                                                                              +            minSize = tmp
                                                                                              +        }
                                                                                              +    }
                                                                                              +
                                                                                              +    if minSize == math.MaxInt32 {
                                                                                              +        minSize = 0
                                                                                              +    }
                                                                                              +    return minSize
                                                                                              +}
                                                                                              +
                                                                                              +func FindMinDiff2(nums []int) int {
                                                                                              +    if len(nums) <= 0="" {="" return="" }="" sort.ints(nums)="" minsize="" :="math.MaxInt32" for="" i="" <="" len(nums);="" i++="" tmp="" -="" nums[i-1])="" if=""> tmp {
                                                                                              +            minSize = tmp
                                                                                              +        }
                                                                                              +    }
                                                                                              +
                                                                                              +    if minSize == math.MaxInt32 {
                                                                                              +        minSize = 0
                                                                                              +    }
                                                                                              +    return minSize
                                                                                              +}
                                                                                              +
                                                                                              +
                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                              + + +
                                                                                              + +
                                                                                              +
                                                                                              +
                                                                                              + +

                                                                                              results matching ""

                                                                                              +
                                                                                                + +
                                                                                                +
                                                                                                + +

                                                                                                No results matching ""

                                                                                                + +
                                                                                                +
                                                                                                +
                                                                                                + +
                                                                                                +
                                                                                                + +
                                                                                                + + + + + + +
                                                                                                + + +
                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..b99f59eee --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Kimi Tsai + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/Leetcode/0000.xxxx/index.html b/Leetcode/0000.xxxx/index.html new file mode 100644 index 000000000..b2f438a28 --- /dev/null +++ b/Leetcode/0000.xxxx/index.html @@ -0,0 +1,3810 @@ + + + + + + + NUM.LEETCODETITLE ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                +
                                                                                                + + + + + + + + +
                                                                                                + +
                                                                                                + +
                                                                                                + + + + + + + + +
                                                                                                +
                                                                                                + +
                                                                                                +
                                                                                                + +
                                                                                                + +

                                                                                                NUM.LEETCODETITLE

                                                                                                題目

                                                                                                +

                                                                                                題目大意

                                                                                                +

                                                                                                解題思路

                                                                                                +

                                                                                                Big O

                                                                                                +
                                                                                                  +
                                                                                                • 時間複雜 : ``
                                                                                                • +
                                                                                                • 空間複雜 : ``
                                                                                                • +
                                                                                                +

                                                                                                來源

                                                                                                + +

                                                                                                解答

                                                                                                +

                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/NUM.FOLDERPATH/main.go

                                                                                                +
                                                                                                
                                                                                                +
                                                                                                +
                                                                                                +

                                                                                                Benchmark

                                                                                                +
                                                                                                
                                                                                                +
                                                                                                +
                                                                                                +
                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                + +
                                                                                                + +
                                                                                                +
                                                                                                +
                                                                                                + +

                                                                                                results matching ""

                                                                                                +
                                                                                                  + +
                                                                                                  +
                                                                                                  + +

                                                                                                  No results matching ""

                                                                                                  + +
                                                                                                  +
                                                                                                  +
                                                                                                  + +
                                                                                                  +
                                                                                                  + +
                                                                                                  + + + + + + +
                                                                                                  + + +
                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0000.xxxx/main.go b/Leetcode/0000.xxxx/main.go new file mode 100644 index 000000000..5d585372b --- /dev/null +++ b/Leetcode/0000.xxxx/main.go @@ -0,0 +1,2 @@ + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() \ No newline at end of file diff --git a/Leetcode/0000.xxxx/main_test.go b/Leetcode/0000.xxxx/main_test.go new file mode 100644 index 000000000..0788b7309 --- /dev/null +++ b/Leetcode/0000.xxxx/main_test.go @@ -0,0 +1,34 @@ +package + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "bbbab", + 4, + }, +} + +func TestLongestPalindromeSubseq(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := LongestPalindromeSubseq(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubseq(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindromeSubseq(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0001.Two-Sum/Merging-2-Packages/index.html b/Leetcode/0001.Two-Sum/Merging-2-Packages/index.html new file mode 100644 index 000000000..73119c75f --- /dev/null +++ b/Leetcode/0001.Two-Sum/Merging-2-Packages/index.html @@ -0,0 +1,3801 @@ + + + + + + + Merging 2 Packages ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                  +
                                                                                                  + + + + + + + + +
                                                                                                  + +
                                                                                                  + +
                                                                                                  + + + + + + + + +
                                                                                                  +
                                                                                                  + +
                                                                                                  +
                                                                                                  + +
                                                                                                  + +

                                                                                                  Given a package with a weight limit limit and an array arr of item weights, implement a function +getIndicesOfItemWeights that finds two items whose sum of weights equals the weight limit. The function should +return a pair [i, j] of the indices of the item weights, ordered such that i > j. If such a pair doesn’t exist, return +an empty array. +input: arr = [4, 6, 10, 15, 16], lim = 21 +output: [3, 1] # since these are the indices of the weights 6 and 15 whose sum equals to 21

                                                                                                  +
                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                  + + +
                                                                                                  + +
                                                                                                  +
                                                                                                  +
                                                                                                  + +

                                                                                                  results matching ""

                                                                                                  +
                                                                                                    + +
                                                                                                    +
                                                                                                    + +

                                                                                                    No results matching ""

                                                                                                    + +
                                                                                                    +
                                                                                                    +
                                                                                                    + +
                                                                                                    +
                                                                                                    + +
                                                                                                    + + + + + + + + + + +
                                                                                                    + + +
                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0001.Two-Sum/Merging-2-Packages/main.go b/Leetcode/0001.Two-Sum/Merging-2-Packages/main.go new file mode 100644 index 000000000..a69343a3f --- /dev/null +++ b/Leetcode/0001.Two-Sum/Merging-2-Packages/main.go @@ -0,0 +1,13 @@ +package merging2packages + +func getIndicesOfItemWeights(arr []int, limit int) []int { + + m := make(map[int]int) + for i, v := range arr { + if _, ok := m[limit-v]; ok { + return []int{i, m[limit-v]} + } + m[v] = i + } + return nil +} diff --git a/Leetcode/0001.Two-Sum/Merging-2-Packages/main_test.go b/Leetcode/0001.Two-Sum/Merging-2-Packages/main_test.go new file mode 100644 index 000000000..36cc43be0 --- /dev/null +++ b/Leetcode/0001.Two-Sum/Merging-2-Packages/main_test.go @@ -0,0 +1,45 @@ +package merging2packages + +import ( + "reflect" + "testing" +) + +func TestGetIndicesOfItemWeights(t *testing.T) { + tests := []struct { + name string + arg1 []int + arg2 int + want []int + }{ + { + name: "getIndicesOfItemWeights", + arg1: []int{4, 6, 10, 15, 16}, + arg2: 21, + want: []int{3, 1}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := getIndicesOfItemWeights(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func BenchmarkGetIndicesOfItemWeights(b *testing.B) { + arg1 := []int{2, 7, 11, 15} + arg2 := 9 + b.ResetTimer() + for i := 0; i < b.N; i++ { + getIndicesOfItemWeights(arg1, arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0001.Two-Sum -bench=. +BenchmarkTwosum-8 53737875 22.04 ns/op 16 B/op 1 allocs/op +BenchmarkTwosum2-8 25733203 44.74 ns/op 16 B/op 1 allocs/op +*/ diff --git a/Leetcode/0001.Two-Sum/index.html b/Leetcode/0001.Two-Sum/index.html new file mode 100644 index 000000000..09257cdfa --- /dev/null +++ b/Leetcode/0001.Two-Sum/index.html @@ -0,0 +1,3862 @@ + + + + + + + 0001.Two Sum ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                    +
                                                                                                    + + + + + + + + +
                                                                                                    + +
                                                                                                    + +
                                                                                                    + + + + + + + + +
                                                                                                    +
                                                                                                    + +
                                                                                                    +
                                                                                                    + +
                                                                                                    + +

                                                                                                    1. Two Sum

                                                                                                    题目

                                                                                                    +

                                                                                                    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

                                                                                                    +

                                                                                                    You may assume that each input would have exactly one solution, and you may not use the same element twice.

                                                                                                    +

                                                                                                    Example:

                                                                                                    +

                                                                                                    Given nums = [2, 7, 11, 15], target = 9,

                                                                                                    +

                                                                                                    Because nums[0] + nums[1] = 2 + 7 = 9, +return [0, 1].

                                                                                                    +

                                                                                                    題目大意

                                                                                                    +

                                                                                                    在數組中找到 2 個數之和等於給定值的數字, 結果返回 2 個數字在數組中的下標.

                                                                                                    +

                                                                                                    解題思路

                                                                                                    +
                                                                                                      +
                                                                                                    • 暴力解: 時間複雜 O(n^2), 空間複雜 O(1)

                                                                                                      +
                                                                                                    • +
                                                                                                    • 這道題最優的做法時間複雜度是 O(n) +順序掃描數組, 對每一個元素,在 map 中找能組合給定值的另一半數字, 如果找到了, 直接返回 2 個數字的下標即可. 如果找不到, 就把這個數字存入 map 中, 等待掃到“另一半”數字的時候, 再取出來返回結果.

                                                                                                      +
                                                                                                    • +
                                                                                                    • 如果nums是有序 可以使用左右指針

                                                                                                      +
                                                                                                    • +
                                                                                                    +

                                                                                                    來源

                                                                                                    + +

                                                                                                    解答

                                                                                                    +

                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0001.Two-Sum/twosum.go

                                                                                                    +
                                                                                                    package twosum
                                                                                                    +
                                                                                                    +// 時間複雜 O(n^2), 空間複雜 O(1)
                                                                                                    +func Twosum(nums []int, target int) []int {
                                                                                                    +    for i, _ := range nums {
                                                                                                    +        for j := i + 1; j < len(nums); j++ {
                                                                                                    +            if target == nums[i]+nums[j] {
                                                                                                    +                return []int{i, j}
                                                                                                    +            }
                                                                                                    +        }
                                                                                                    +    }
                                                                                                    +    return []int{0, 0}
                                                                                                    +}
                                                                                                    +
                                                                                                    +func Twosum2(nums []int, target int) []int {
                                                                                                    +    m := make(map[int]int)
                                                                                                    +    for i, v := range nums {
                                                                                                    +        if idx, ok := m[target-v]; ok {
                                                                                                    +            return []int{idx, i}
                                                                                                    +        }
                                                                                                    +        m[v] = i
                                                                                                    +    }
                                                                                                    +    return []int{0, 0}
                                                                                                    +}
                                                                                                    +
                                                                                                    +// 如果nums是有序 可以使用左右指針
                                                                                                    +// func Twosum3(nums []int, target int) []int {
                                                                                                    +//     left, right := 0, len(nums)-1
                                                                                                    +//     sort.Ints(nums)
                                                                                                    +
                                                                                                    +//     for left < right {
                                                                                                    +//         sum := nums[left] + nums[right]
                                                                                                    +//         if sum == target {
                                                                                                    +//             return []int{left, right}
                                                                                                    +//         } else if sum < target {
                                                                                                    +//             left++
                                                                                                    +//         } else if sum > target {
                                                                                                    +//             right--
                                                                                                    +//         }
                                                                                                    +//     }
                                                                                                    +//     return []int{0, 0}
                                                                                                    +// }
                                                                                                    +
                                                                                                    +
                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                    + +
                                                                                                    + +
                                                                                                    +
                                                                                                    +
                                                                                                    + +

                                                                                                    results matching ""

                                                                                                    +
                                                                                                      + +
                                                                                                      +
                                                                                                      + +

                                                                                                      No results matching ""

                                                                                                      + +
                                                                                                      +
                                                                                                      +
                                                                                                      + +
                                                                                                      +
                                                                                                      + +
                                                                                                      + + + + + + + + + + +
                                                                                                      + + +
                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0001.Two-Sum/twosum.go b/Leetcode/0001.Two-Sum/twosum.go new file mode 100644 index 000000000..b11839dc9 --- /dev/null +++ b/Leetcode/0001.Two-Sum/twosum.go @@ -0,0 +1,42 @@ +package twosum + +// ๆ™‚้–“่ค‡้›œ O(n^2), ็ฉบ้–“่ค‡้›œ O(1) +func Twosum(nums []int, target int) []int { + for i, _ := range nums { + for j := i + 1; j < len(nums); j++ { + if target == nums[i]+nums[j] { + return []int{i, j} + } + } + } + return []int{0, 0} +} + +func Twosum2(nums []int, target int) []int { + m := make(map[int]int) + for i, v := range nums { + if idx, ok := m[target-v]; ok { + return []int{idx, i} + } + m[v] = i + } + return []int{0, 0} +} + +// ๅฆ‚ๆžœnumsๆ˜ฏๆœ‰ๅบ ๅฏไปฅไฝฟ็”จๅทฆๅณๆŒ‡้‡ +// func Twosum3(nums []int, target int) []int { +// left, right := 0, len(nums)-1 +// sort.Ints(nums) + +// for left < right { +// sum := nums[left] + nums[right] +// if sum == target { +// return []int{left, right} +// } else if sum < target { +// left++ +// } else if sum > target { +// right-- +// } +// } +// return []int{0, 0} +// } diff --git a/Leetcode/0001.Two-Sum/twosum_test.go b/Leetcode/0001.Two-Sum/twosum_test.go new file mode 100644 index 000000000..04788e757 --- /dev/null +++ b/Leetcode/0001.Two-Sum/twosum_test.go @@ -0,0 +1,78 @@ +package twosum + +import ( + "reflect" + "testing" +) + +func TestTwosum(t *testing.T) { + tests := []struct { + name string + arg1 []int + arg2 int + want []int + }{ + { + name: "Twosum", + arg1: []int{2, 7, 11, 15}, + arg2: 9, + want: []int{0, 1}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Twosum(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestTwosum2(t *testing.T) { + tests := []struct { + name string + arg1 []int + arg2 int + want []int + }{ + { + name: "Twosum2", + arg1: []int{2, 7, 11, 15}, + arg2: 9, + want: []int{0, 1}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Twosum2(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func BenchmarkTwosum(b *testing.B) { + arg1 := []int{2, 7, 11, 15} + arg2 := 9 + b.ResetTimer() + for i := 0; i < b.N; i++ { + Twosum(arg1, arg2) + } +} + +func BenchmarkTwosum2(b *testing.B) { + arg1 := []int{2, 7, 11, 15} + arg2 := 9 + b.ResetTimer() + for i := 0; i < b.N; i++ { + Twosum2(arg1, arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0001.Two-Sum -bench=. +BenchmarkTwosum-8 53737875 22.04 ns/op 16 B/op 1 allocs/op +BenchmarkTwosum2-8 25733203 44.74 ns/op 16 B/op 1 allocs/op +*/ diff --git a/Leetcode/0002.Add-Two-Numbers/index.html b/Leetcode/0002.Add-Two-Numbers/index.html new file mode 100644 index 000000000..325771415 --- /dev/null +++ b/Leetcode/0002.Add-Two-Numbers/index.html @@ -0,0 +1,3860 @@ + + + + + + + 0002.Add Two Numbers ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                      +
                                                                                                      + + + + + + + + +
                                                                                                      + +
                                                                                                      + +
                                                                                                      + + + + + + + + +
                                                                                                      +
                                                                                                      + +
                                                                                                      +
                                                                                                      + +
                                                                                                      + +

                                                                                                      0002.Add Two Numbers

                                                                                                      題目

                                                                                                      +

                                                                                                      題目大意

                                                                                                      +

                                                                                                      解題思路

                                                                                                      +

                                                                                                      鏈表雙指標技巧 和加法運算過程中對進位的處理。 注意這個 carry 變數的處理,在我們手動類比加法過程的時候會經常用到。

                                                                                                      +
                                                                                                        +
                                                                                                      • 遍歷 l1跟 l2. 講兩個list的val相加, 並且記錄進位的值給next使用
                                                                                                      • +
                                                                                                      • 最後如果 carry 還有的話, 需要產生一個新的節點
                                                                                                      • +
                                                                                                      +

                                                                                                      Big O

                                                                                                      +
                                                                                                        +
                                                                                                      • 時間複雜 : O(max⁡(m,n) +時間複雜度: O(max⁡(m,n)) ,其中 m 和 n 分別為兩個鏈表的長度。 我們要遍歷兩個鏈表的全部位置,而處理每個位置只需要 O(1) 的時間

                                                                                                        +
                                                                                                      • +
                                                                                                      • 空間複雜 : O(1) +O(1) 。 注意返回值不計入空間複雜度

                                                                                                        +
                                                                                                      • +
                                                                                                      +

                                                                                                      來源

                                                                                                      + +

                                                                                                      解答

                                                                                                      +

                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0002.Add-Two-Numbers/main.go

                                                                                                      +
                                                                                                      package addtwonumbers
                                                                                                      +
                                                                                                      +// 時間複雜 O(max(m,n)), 空間複雜 O(1)
                                                                                                      +/**
                                                                                                      + * Definition for singly-linked list.
                                                                                                      + * type ListNode struct {
                                                                                                      + *     Val int
                                                                                                      + *     Next *ListNode
                                                                                                      + * }
                                                                                                      + */
                                                                                                      +
                                                                                                      +// 遍歷 l1跟 l2. 講兩個list的val相加, 並且記錄進位的值給next使用
                                                                                                      +// 最後如果 carry 還有的話, 需要產生一個新的節點
                                                                                                      +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
                                                                                                      +    var result, tail *ListNode
                                                                                                      +    carry := 0
                                                                                                      +    for l1 != nil || l2 != nil {
                                                                                                      +        n1, n2 := 0, 0
                                                                                                      +        if l1 != nil {
                                                                                                      +            n1 = l1.Val
                                                                                                      +            l1 = l1.Next
                                                                                                      +        }
                                                                                                      +        if l2 != nil {
                                                                                                      +            n2 = l2.Val
                                                                                                      +            l2 = l2.Next
                                                                                                      +        }
                                                                                                      +        sum := n1 + n2 + carry
                                                                                                      +        sum, carry = sum%10, sum/10
                                                                                                      +
                                                                                                      +        if result == nil {
                                                                                                      +            result = &ListNode{Val: sum, Next: nil}
                                                                                                      +            tail = result
                                                                                                      +        } else {
                                                                                                      +            tail.Next = &ListNode{Val: sum, Next: nil}
                                                                                                      +            tail = tail.Next
                                                                                                      +        }
                                                                                                      +    }
                                                                                                      +    // 最後如果 carry 還有的話, 需要產生一個新的節點
                                                                                                      +    if carry > 0 {
                                                                                                      +        tail.Next = &ListNode{Val: carry, Next: nil}
                                                                                                      +    }
                                                                                                      +    return result
                                                                                                      +}
                                                                                                      +
                                                                                                      +

                                                                                                      Benchmark

                                                                                                      +
                                                                                                      
                                                                                                      +
                                                                                                      +
                                                                                                      +
                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                      + +
                                                                                                      + +
                                                                                                      +
                                                                                                      +
                                                                                                      + +

                                                                                                      results matching ""

                                                                                                      +
                                                                                                        + +
                                                                                                        +
                                                                                                        + +

                                                                                                        No results matching ""

                                                                                                        + +
                                                                                                        +
                                                                                                        +
                                                                                                        + +
                                                                                                        +
                                                                                                        + +
                                                                                                        + + + + + + +
                                                                                                        + + +
                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0002.Add-Two-Numbers/main.go b/Leetcode/0002.Add-Two-Numbers/main.go new file mode 100644 index 000000000..a0ae04415 --- /dev/null +++ b/Leetcode/0002.Add-Two-Numbers/main.go @@ -0,0 +1,43 @@ +package addtwonumbers + +// ๆ™‚้–“่ค‡้›œ O(max(m,n)), ็ฉบ้–“่ค‡้›œ O(1) +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + +// ้ๆญท l1่ทŸ l2. ่ฌ›ๅ…ฉๅ€‹list็š„val็›ธๅŠ , ไธฆไธ”่จ˜้Œ„้€ฒไฝ็š„ๅ€ผ็ตฆnextไฝฟ็”จ +// ๆœ€ๅพŒๅฆ‚ๆžœ carry ้‚„ๆœ‰็š„่ฉฑ, ้œ€่ฆ็”ข็”Ÿไธ€ๅ€‹ๆ–ฐ็š„็ฏ€้ปž +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + var result, tail *ListNode + carry := 0 + for l1 != nil || l2 != nil { + n1, n2 := 0, 0 + if l1 != nil { + n1 = l1.Val + l1 = l1.Next + } + if l2 != nil { + n2 = l2.Val + l2 = l2.Next + } + sum := n1 + n2 + carry + sum, carry = sum%10, sum/10 + + if result == nil { + result = &ListNode{Val: sum, Next: nil} + tail = result + } else { + tail.Next = &ListNode{Val: sum, Next: nil} + tail = tail.Next + } + } + // ๆœ€ๅพŒๅฆ‚ๆžœ carry ้‚„ๆœ‰็š„่ฉฑ, ้œ€่ฆ็”ข็”Ÿไธ€ๅ€‹ๆ–ฐ็š„็ฏ€้ปž + if carry > 0 { + tail.Next = &ListNode{Val: carry, Next: nil} + } + return result +} diff --git a/Leetcode/0002.Add-Two-Numbers/main_test.go b/Leetcode/0002.Add-Two-Numbers/main_test.go new file mode 100644 index 000000000..7edcb537d --- /dev/null +++ b/Leetcode/0002.Add-Two-Numbers/main_test.go @@ -0,0 +1,35 @@ +// TODO : 0002.Add-Two-Numbers Unit Test +package + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "bbbab", + 4, + }, +} + +func TestLongestPalindromeSubseq(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := LongestPalindromeSubseq(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubseq(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindromeSubseq(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters.go b/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters.go new file mode 100644 index 000000000..eca9b4678 --- /dev/null +++ b/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters.go @@ -0,0 +1,94 @@ +package longestSubstringwithoutrepeatingcharacters + +// LengthOfLongestSubstring ๆšดๅŠ›่งฃ +func LengthOfLongestSubstring(s string) int { + slength := len(s) + if slength == 0 || slength == 1 { + return slength + } + + tmpLen := 1 + var maxLen = 1 + + for i := 1; i < slength; i++ { + // ๅพ€ๅ‰ๆ‰พๅ‰ๅนพๅ€‹่ฆ–็ช— + j := i - tmpLen + + for ; j < i; j++ { + if s[j] == s[i] { // ๅฆ‚ๆžœ็›ธๅŒ๏ผŒ้‚ฃ้บผๅ’ŒS[J]ๅˆฐS[I-1]ไธญ้–“็š„่‚ฏๅฎšไธ็›ธๅŒ๏ผŒๆ‰€ไปฅๅฏไปฅ็›ดๆŽฅ่จˆ็ฎ—ๅพ—ๅˆฐ + tmpLen = i - j + break + } + } + + if j == i { // ้ƒฝไธ็›ธๅŒ + tmpLen++ + } + + if tmpLen > maxLen { + maxLen = tmpLen + } + } + + return maxLen +} + +// LengthOfLongestSubstringMap ็”จmap ็ด€้Œ„ๆ˜ฏๅฆ้‡่ค‡. +func LengthOfLongestSubstringMap(s string) int { + slength := len(s) + if slength == 0 || slength == 1 { + return slength + } + + charMap := make(map[byte]bool) + maxLen, left, right := 0, 0, 0 + + for left < slength { + if ok := charMap[s[right]]; ok { + // ๆœ‰ๆ‰พๅˆฐ + charMap[s[left]] = false + left++ + } else { + charMap[s[right]] = true + right++ + } + if maxLen < right-left { + maxLen = right - left + } + if (left+maxLen) >= slength || right >= len(s) { + break + } + } + + return maxLen +} + +// LengthOfLongestSubstringBit ็”จmapๆ•ˆ่ƒฝไธๅฅฝๆ™‚ๅฏไฝฟ็”จๆ•ธ็ต„ๆ”นๅ–„ +func LengthOfLongestSubstringBit(s string) int { + slength := len(s) + if slength == 0 || slength == 1 { + return slength + } + + // ASCII 0~255 + charMap := [256]bool{} + maxLen, left, right := 0, 0, 0 + for left < slength { + if ok := charMap[s[right]]; ok { + // ๆœ‰ๆ‰พๅˆฐ + charMap[s[left]] = false + left++ + } else { + charMap[s[right]] = true + right++ + } + + if maxLen < right-left { + maxLen = right - left + } + if left+maxLen >= slength || right >= len(s) { + break + } + } + return maxLen +} diff --git a/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters_test.go b/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters_test.go new file mode 100644 index 000000000..3c531fbbd --- /dev/null +++ b/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters_test.go @@ -0,0 +1,93 @@ +package longestSubstringwithoutrepeatingcharacters + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 string + want int +}{ + { + arg1: "abcabcbb", + want: 3, + }, + { + arg1: "bbbbbb", + want: 1, + }, + { + arg1: "pwwkew", + want: 3, + }, + { + arg1: "", + want: 0, + }, + { + arg1: "aab", + want: 2, + }, +} + +func TestLengthOfLongestSubstring(t *testing.T) { + for _, tt := range tests { + if got := LengthOfLongestSubstring(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestLengthOfLongestSubstringMap(t *testing.T) { + for _, tt := range tests { + if got := LengthOfLongestSubstringMap(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestLengthOfLongestSubstringBit(t *testing.T) { + for _, tt := range tests { + if got := LengthOfLongestSubstringBit(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLengthOfLongestSubstring(b *testing.B) { + arg1 := "abcabcbb" + b.ResetTimer() + for i := 0; i < b.N; i++ { + LengthOfLongestSubstring(arg1) + } +} + +func BenchmarkLengthOfLongestSubstringMap(b *testing.B) { + arg1 := "abcabcbb" + b.ResetTimer() + for i := 0; i < b.N; i++ { + LengthOfLongestSubstringMap(arg1) + } +} + +func BenchmarkLengthOfLongestSubstringBit(b *testing.B) { + arg1 := "abcabcbb" + b.ResetTimer() + for i := 0; i < b.N; i++ { + LengthOfLongestSubstringBit(arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkLengthOfLongestSubstring-8 67657353 19.30 ns/op 0 B/op 0 allocs/op +BenchmarkLengthOfLongestSubstringMap-8 2463084 483.5 ns/op 0 B/op 0 allocs/op +BenchmarkLengthOfLongestSubstringBit-8 53792877 21.70 ns/op 0 B/op 0 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters 5.125s +*/ diff --git a/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/index.html b/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/index.html new file mode 100644 index 000000000..8ff6e85fe --- /dev/null +++ b/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/index.html @@ -0,0 +1,3926 @@ + + + + + + + 0003.Longest Substring Without Repeating Characters ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                        +
                                                                                                        + + + + + + + + +
                                                                                                        + +
                                                                                                        + +
                                                                                                        + + + + + + + + +
                                                                                                        +
                                                                                                        + +
                                                                                                        +
                                                                                                        + +
                                                                                                        + +

                                                                                                        3. Longest Substring Without Repeating Characters

                                                                                                        题目

                                                                                                        +

                                                                                                        Given a string, find the length of the longest substring without repeating characters.

                                                                                                        +

                                                                                                        Example 1:

                                                                                                        +
                                                                                                        Input: "abcabcbb"
                                                                                                        +Output: 3
                                                                                                        +Explanation: The answer is "abc", with the length of 3.
                                                                                                        +
                                                                                                        +

                                                                                                        Example 2:

                                                                                                        +
                                                                                                        Input: "bbbbb"
                                                                                                        +Output: 1
                                                                                                        +Explanation: The answer is "b", with the length of 1.
                                                                                                        +
                                                                                                        +

                                                                                                        Example 3:

                                                                                                        +
                                                                                                        Input: "pwwkew"
                                                                                                        +Output: 3
                                                                                                        +Explanation: The answer is "wke", with the length of 3.
                                                                                                        +Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
                                                                                                        +
                                                                                                        +

                                                                                                        題目大意

                                                                                                        +

                                                                                                        在一個字符串重尋找沒有重複字母的最長子串。

                                                                                                        +

                                                                                                        解題思路

                                                                                                        +

                                                                                                        這一題和第 438 題,第 3 題,第 76 題,第 567 題類似,用的思想都是"滑動窗口"。

                                                                                                        +

                                                                                                        滑動窗口的右邊界不斷的右移,只要沒有重複的字符,就持續向右擴大窗口邊界。一旦出現了重複字符,就需要縮小左邊界,直到重複的字符移出了左邊界,然後繼續移動滑動窗口的右邊界。以此類推,每次移動需要計算當前長度,並判斷是否需要更新最大長度,最終最大的值就是題目中的所求。

                                                                                                        +

                                                                                                        O(n)

                                                                                                        +

                                                                                                        用空間換取時間, map紀錄已出現過的字符, 如果map效能不好時可使用數組(Slice)來改善

                                                                                                        +

                                                                                                        來源

                                                                                                        + +

                                                                                                        解答

                                                                                                        +

                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters.go

                                                                                                        +
                                                                                                        package longestSubstringwithoutrepeatingcharacters
                                                                                                        +
                                                                                                        +// LengthOfLongestSubstring 暴力解
                                                                                                        +func LengthOfLongestSubstring(s string) int {
                                                                                                        +    slength := len(s)
                                                                                                        +    if slength == 0 || slength == 1 {
                                                                                                        +        return slength
                                                                                                        +    }
                                                                                                        +
                                                                                                        +    tmpLen := 1
                                                                                                        +    var maxLen = 1
                                                                                                        +
                                                                                                        +    for i := 1; i < slength; i++ {
                                                                                                        +        // 往前找前幾個視窗
                                                                                                        +        j := i - tmpLen
                                                                                                        +
                                                                                                        +        for ; j < i; j++ {
                                                                                                        +            if s[j] == s[i] { // 如果相同,那麼和S[J]到S[I-1]中間的肯定不相同,所以可以直接計算得到
                                                                                                        +                tmpLen = i - j
                                                                                                        +                break
                                                                                                        +            }
                                                                                                        +        }
                                                                                                        +
                                                                                                        +        if j == i { // 都不相同
                                                                                                        +            tmpLen++
                                                                                                        +        }
                                                                                                        +
                                                                                                        +        if tmpLen > maxLen {
                                                                                                        +            maxLen = tmpLen
                                                                                                        +        }
                                                                                                        +    }
                                                                                                        +
                                                                                                        +    return maxLen
                                                                                                        +}
                                                                                                        +
                                                                                                        +// LengthOfLongestSubstringMap 用map 紀錄是否重複.
                                                                                                        +func LengthOfLongestSubstringMap(s string) int {
                                                                                                        +    slength := len(s)
                                                                                                        +    if slength == 0 || slength == 1 {
                                                                                                        +        return slength
                                                                                                        +    }
                                                                                                        +
                                                                                                        +    charMap := make(map[byte]bool)
                                                                                                        +    maxLen, left, right := 0, 0, 0
                                                                                                        +
                                                                                                        +    for left < slength {
                                                                                                        +        if ok := charMap[s[right]]; ok {
                                                                                                        +            // 有找到
                                                                                                        +            charMap[s[left]] = false
                                                                                                        +            left++
                                                                                                        +        } else {
                                                                                                        +            charMap[s[right]] = true
                                                                                                        +            right++
                                                                                                        +        }
                                                                                                        +        if maxLen < right-left {
                                                                                                        +            maxLen = right - left
                                                                                                        +        }
                                                                                                        +        if (left+maxLen) >= slength || right >= len(s) {
                                                                                                        +            break
                                                                                                        +        }
                                                                                                        +    }
                                                                                                        +
                                                                                                        +    return maxLen
                                                                                                        +}
                                                                                                        +
                                                                                                        +// LengthOfLongestSubstringBit 用map效能不好時可使用數組改善
                                                                                                        +func LengthOfLongestSubstringBit(s string) int {
                                                                                                        +    slength := len(s)
                                                                                                        +    if slength == 0 || slength == 1 {
                                                                                                        +        return slength
                                                                                                        +    }
                                                                                                        +
                                                                                                        +    // ASCII 0~255
                                                                                                        +    charMap := [256]bool{}
                                                                                                        +    maxLen, left, right := 0, 0, 0
                                                                                                        +    for left < slength {
                                                                                                        +        if ok := charMap[s[right]]; ok {
                                                                                                        +            // 有找到
                                                                                                        +            charMap[s[left]] = false
                                                                                                        +            left++
                                                                                                        +        } else {
                                                                                                        +            charMap[s[right]] = true
                                                                                                        +            right++
                                                                                                        +        }
                                                                                                        +
                                                                                                        +        if maxLen < right-left {
                                                                                                        +            maxLen = right - left
                                                                                                        +        }
                                                                                                        +        if left+maxLen >= slength || right >= len(s) {
                                                                                                        +            break
                                                                                                        +        }
                                                                                                        +    }
                                                                                                        +    return maxLen
                                                                                                        +}
                                                                                                        +
                                                                                                        +

                                                                                                        Benchmark

                                                                                                        +
                                                                                                        goos: darwin
                                                                                                        +goarch: amd64
                                                                                                        +pkg: LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters
                                                                                                        +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                        +BenchmarkLengthOfLongestSubstring-8             66143602                19.08 ns/op            0 B/op          0 allocs/op
                                                                                                        +BenchmarkLengthOfLongestSubstringMap-8           2524627               397.8 ns/op             0 B/op          0 allocs/op
                                                                                                        +BenchmarkLengthOfLongestSubstringBit-8          65099846                21.37 ns/op            0 B/op          0 allocs/op
                                                                                                        +PASS
                                                                                                        +ok      LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters     4.193s
                                                                                                        +
                                                                                                        +
                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                        + +
                                                                                                        + +
                                                                                                        +
                                                                                                        +
                                                                                                        + +

                                                                                                        results matching ""

                                                                                                        +
                                                                                                          + +
                                                                                                          +
                                                                                                          + +

                                                                                                          No results matching ""

                                                                                                          + +
                                                                                                          +
                                                                                                          +
                                                                                                          + +
                                                                                                          +
                                                                                                          + +
                                                                                                          + + + + + + +
                                                                                                          + + +
                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0005.Longest-Palindromic-Substring/0005.LongestPalindromicString.jpg b/Leetcode/0005.Longest-Palindromic-Substring/0005.LongestPalindromicString.jpg new file mode 100644 index 000000000..eef3eb972 Binary files /dev/null and b/Leetcode/0005.Longest-Palindromic-Substring/0005.LongestPalindromicString.jpg differ diff --git a/Leetcode/0005.Longest-Palindromic-Substring/index.html b/Leetcode/0005.Longest-Palindromic-Substring/index.html new file mode 100644 index 000000000..10dff74f8 --- /dev/null +++ b/Leetcode/0005.Longest-Palindromic-Substring/index.html @@ -0,0 +1,3836 @@ + + + + + + + 0005. Longest Palindromic Substring ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                          +
                                                                                                          + + + + + + + + +
                                                                                                          + +
                                                                                                          + +
                                                                                                          + + + + + + + + +
                                                                                                          +
                                                                                                          + +
                                                                                                          +
                                                                                                          + +
                                                                                                          + +

                                                                                                          0005.Longest Palindromic Substring

                                                                                                          題目

                                                                                                          +

                                                                                                          Given a string s, return the longest palindromic substring in s.

                                                                                                          +

                                                                                                          A string is called a palindrome string if the reverse of that string is the same as the original string.

                                                                                                          +

                                                                                                          Example 1:

                                                                                                          +
                                                                                                          Input: s = "babad"
                                                                                                          +Output: "bab"
                                                                                                          +Explanation: "aba" is also a valid answer.
                                                                                                          +

                                                                                                          Example 2:

                                                                                                          +
                                                                                                          Input: s = "cbbd"
                                                                                                          +Output: "bb"
                                                                                                          +

                                                                                                          Constraints:

                                                                                                          +
                                                                                                            +
                                                                                                          • 1 <= s.length <= 1000
                                                                                                          • +
                                                                                                          • s consist of only digits and English letters.
                                                                                                          • +
                                                                                                          +

                                                                                                          題目大意

                                                                                                          +

                                                                                                          給你一個字符串 s,找到 s 中最長的回文子串。

                                                                                                          +

                                                                                                          解題思路

                                                                                                          +
                                                                                                            +
                                                                                                          • 每一個字符本身都是回文
                                                                                                          • +
                                                                                                          • 長度為 2, 且首尾字符相同則為回文
                                                                                                          • +
                                                                                                          • 長度>=3, 如果頭尾相同, 則去掉頭尾後可看是合是回文. 如果頭尾不同則不是回文
                                                                                                          • +
                                                                                                          +

                                                                                                          +

                                                                                                          來源

                                                                                                          + +

                                                                                                          解答

                                                                                                          +
                                                                                                          package longestpalindromicsubstring
                                                                                                          +
                                                                                                          +func longestPalindrome(s string) string {
                                                                                                          +    dp := make([][]bool, len(s))
                                                                                                          +    result := s[0:1]
                                                                                                          +
                                                                                                          +    for i := 0; i < len(s); i++ {
                                                                                                          +        dp[i] = make([]bool, len(s))
                                                                                                          +        dp[i][i] = true // 每個字符本身都是回文
                                                                                                          +    }
                                                                                                          +    for length := 2; length <= 1="" 3="" len(s);="" length++="" {="" for="" start="" :="0;" <="" len(s)-length+1;="" start++="" end="" +="" length="" -="" if="" s[start]="" !="s[end]" ๅญ—้ ญๅญ—ๅฐพไธๅŒ,="" ไธๆ˜ฏๅ›žๆ–‡="" continue="" }="" else="" ้•ทๅบฆ็‚บ2ไธ”ๅญ—้ ญๅญ—ๅฐพ็›ธๅŒ,="" ๅ‰‡็‚บๅ›žๆ–‡="" dp[start][end]="true" ็‹€ๆ…‹่ฝ‰็งป="" ๅŽปๆŽ‰ๅญ—้ ญๅญ—ๅฐพ,="" ๅˆคๆ–ทๆ˜ฏๅฆ้‚„ๆ˜ฏๅ›žๆ–‡="" &&="" (end-start+1)=""> len(result) {
                                                                                                          +                result = s[start : end+1]
                                                                                                          +            }
                                                                                                          +        }
                                                                                                          +    }
                                                                                                          +    return result
                                                                                                          +}
                                                                                                          +
                                                                                                          +
                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                          + +
                                                                                                          + +
                                                                                                          +
                                                                                                          +
                                                                                                          + +

                                                                                                          results matching ""

                                                                                                          +
                                                                                                            + +
                                                                                                            +
                                                                                                            + +

                                                                                                            No results matching ""

                                                                                                            + +
                                                                                                            +
                                                                                                            +
                                                                                                            + +
                                                                                                            +
                                                                                                            + +
                                                                                                            + + + + + + +
                                                                                                            + + +
                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0005.Longest-Palindromic-Substring/main.go b/Leetcode/0005.Longest-Palindromic-Substring/main.go new file mode 100644 index 000000000..005357236 --- /dev/null +++ b/Leetcode/0005.Longest-Palindromic-Substring/main.go @@ -0,0 +1,30 @@ +package longestpalindromicsubstring + +func longestPalindrome(s string) string { + dp := make([][]bool, len(s)) + result := s[0:1] + + for i := 0; i < len(s); i++ { + dp[i] = make([]bool, len(s)) + dp[i][i] = true // ๆฏๅ€‹ๅญ—็ฌฆๆœฌ่บซ้ƒฝๆ˜ฏๅ›žๆ–‡ + } + for length := 2; length <= len(s); length++ { + for start := 0; start < len(s)-length+1; start++ { + end := start + length - 1 + if s[start] != s[end] { + // ๅญ—้ ญๅญ—ๅฐพไธๅŒ, ไธๆ˜ฏๅ›žๆ–‡ + continue + } else if length < 3 { + // ้•ทๅบฆ็‚บ2ไธ”ๅญ—้ ญๅญ—ๅฐพ็›ธๅŒ, ๅ‰‡็‚บๅ›žๆ–‡ + dp[start][end] = true + } else { + // ็‹€ๆ…‹่ฝ‰็งป : ๅŽปๆŽ‰ๅญ—้ ญๅญ—ๅฐพ, ๅˆคๆ–ทๆ˜ฏๅฆ้‚„ๆ˜ฏๅ›žๆ–‡ + dp[start][end] = dp[start+1][end-1] + } + if dp[start][end] && (end-start+1) > len(result) { + result = s[start : end+1] + } + } + } + return result +} diff --git a/Leetcode/0005.Longest-Palindromic-Substring/main_test.go b/Leetcode/0005.Longest-Palindromic-Substring/main_test.go new file mode 100644 index 000000000..fa0d85bf5 --- /dev/null +++ b/Leetcode/0005.Longest-Palindromic-Substring/main_test.go @@ -0,0 +1,37 @@ +package longestpalindromicsubstring + +import "testing" + +var tests = []struct { + arg1 string + want string +}{ + { + "babad", + "bab", + }, + { + "cbbd", + "bb", + }, +} + +func TestLongestPalindromeSubstring(t *testing.T) { + for _, tt := range tests { + if got := longestPalindrome(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubstring(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + longestPalindrome(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0015.3Sum/3Sum.go b/Leetcode/0015.3Sum/3Sum.go new file mode 100644 index 000000000..0a5c986b1 --- /dev/null +++ b/Leetcode/0015.3Sum/3Sum.go @@ -0,0 +1,141 @@ +package threesum + +import ( + "sort" +) + +// ThreeSumBurst : ๆšดๅŠ›่งฃ : O(n^3) +func ThreeSumBurst(nums []int) [][]int { + result := [][]int{} + sort.Ints(nums) // O(n log n) + for i := 0; i < len(nums); i++ { + // ้œ€่ฆ่ทŸไธŠไธ€ๆฌกไธๅŒ + if i > 0 && nums[i] == nums[i-1] { + continue + } + for j := i + 1; j < len(nums); j++ { + // ้œ€่ฆ่ทŸไธŠไธ€ๆฌกไธๅŒ + if j > i+1 && nums[j] == nums[j-1] { + continue + } + for k := j + 1; k < len(nums); k++ { + if nums[i]+nums[j]+nums[k] == 0 { + result = append(result, []int{nums[i], nums[j], nums[k]}) + } + } + } + } + return result +} + +/* +ThreeSumDoublePoint : ๆœ€ไฝณ่งฃ, ๆŽ’ๅบ + ้›™ๆŒ‡้‡ๆณ• (ๆป‘ๅ‹•่ฆ–็ช—) O(n^2) +1. ็‰นๅˆค๏ผŒๅฐๆ–ผๆ•ธ็ต„้•ทๅบฆ n๏ผŒๅฆ‚ๆžœๆ•ธ็ต„็‚บ null ๆˆ–่€…ๆ•ธ็ต„้•ทๅบฆๅฐๆ–ผ 3๏ผŒ่ฟ”ๅ›ž []ใ€‚ +2. ๅฐๆ•ธ็ต„้€ฒ่กŒๆŽ’ๅบใ€‚ +3. ้ๆญทๆŽ’ๅบๅพŒๆ•ธ็ต„๏ผš + - ๅฐๆ–ผ้‡่ค‡ๅ…ƒ็ด ๏ผš่ทณ้Ž๏ผŒ้ฟๅ…ๅ‡บ็พ้‡่ค‡่งฃ + - ไปคๅทฆๆŒ‡้‡ L=i+1๏ผŒๅณๆŒ‡้‡ R=nโˆ’1๏ผŒ็•ถ L 1 && nums[i] == nums[i-1] { + // ๅŽปๆŽ‰้‡่ค‡ + start = i - 1 + } + for start < i && end > i { + if start > 0 && nums[start] == nums[start-1] { + // ๅŽปๆŽ‰้‡่ค‡ + start++ + continue + } + if end < (len(nums)-1) && nums[end] == nums[end+1] { + // ๅŽปๆŽ‰้‡่ค‡ + end-- + continue + } + addNum = nums[start] + nums[end] + nums[i] + if addNum == 0 { + result = append(result, []int{nums[start], nums[i], nums[end]}) + start++ + end-- + } else if addNum > 0 { + end-- + } else { + start++ + } + } + } + return result +} + +func ThreeSumHashTable(nums []int) [][]int { + result := [][]int{} + if len(nums) < 3 { + return result + } + sort.Ints(nums) // O(n log n) + + for i := 0; i < len(nums)-2; i++ { + // ้ฟๅ…้‡่ค‡็š„่ตทๅง‹ๅ…ƒ็ด  + if i > 0 && nums[i] == nums[i-1] { + continue + } + + seen := make(map[int]bool) + target := -nums[i] // ็›ฎๆจ™ๅ€ผ็‚บ็•ถๅ‰ๅ…ƒ็ด ็š„็›ธๅๆ•ธ + for j := i + 1; j < len(nums); j++ { + complement := target - nums[j] // ๆ‰พๅˆฐ่ˆ‡็•ถๅ‰ๅ…ƒ็ด ้…ๅฐ็š„็›ฎๆจ™ๅ…ƒ็ด  + if seen[complement] { + result = append(result, []int{nums[i], complement, nums[j]}) + // ้ฟๅ…้‡่ค‡็š„้…ๅฐๅ…ƒ็ด  + for j < len(nums)-1 && nums[j] == nums[j+1] { + j++ + } + } + seen[nums[j]] = true + } + } + return result +} + +func ThreeSumTwoPointer(nums []int) [][]int { + result := [][]int{} + sort.Ints(nums) + + for i := 0; i < len(nums)-2; i++ { + if i > 0 && nums[i] == nums[i-1] { + continue + } + target, l, r := -nums[i], i+1, len(nums)-1 + for l < r { + sum := nums[l] + nums[r] + if sum == target { + result = append(result, []int{nums[i], nums[l], nums[r]}) + l++ + r-- + for l < r && nums[l] == nums[l-1] { + l++ + } + for l < r && nums[r] == nums[r+1] { + r-- + } + } else if sum > target { + r-- + } else if sum < target { + l++ + } + } + } + return result +} diff --git a/Leetcode/0015.3Sum/3Sum_test.go b/Leetcode/0015.3Sum/3Sum_test.go new file mode 100644 index 000000000..6a6537695 --- /dev/null +++ b/Leetcode/0015.3Sum/3Sum_test.go @@ -0,0 +1,126 @@ +package threesum + +import ( + "reflect" + "sort" + "testing" +) + +var tests = []struct { + arg1 []int + want [][]int +}{ + { + []int{0, 0, 0}, + [][]int{{0, 0, 0}}, + }, + { + []int{0, 0, 0, 0}, + [][]int{{0, 0, 0}}, + }, + { + []int{-1, 0, 1, 2, -1, -4}, + [][]int{{-1, -1, 2}, {-1, 0, 1}}, + }, + { + []int{}, + [][]int{}, + }, + { + []int{0}, + [][]int{}, + }, +} + +func TestThreeSumBurst(t *testing.T) { + for _, tt := range tests { + if got := ThreeSumBurst(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestThreeSumDoublePoint(t *testing.T) { + for _, tt := range tests { + if got := ThreeSumDoublePoint(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +// ๅˆคๆ–ญๅˆ‡็‰‡ๅœจ่ฏๅ…ธๅบไธŠ็š„ๅคงๅฐๅ…ณ็ณป +func lexicographicLess(a, b []int) bool { + for i := 0; i < len(a) && i < len(b); i++ { + if a[i] < b[i] { + return true + } else if a[i] > b[i] { + return false + } + } + return len(a) < len(b) +} + +// ๅฏนๅˆ‡็‰‡็š„ๅˆ‡็‰‡่ฟ›่กŒๆŽ’ๅบ +func sortSliceOfSlices(s [][]int) [][]int { + sort.Slice(s, func(i, j int) bool { + return lexicographicLess(s[i], s[j]) + }) + return s +} + +func TestThreeSumHashTable(t *testing.T) { + for _, tt := range tests { + if got := ThreeSumHashTable(tt.arg1); !reflect.DeepEqual(sortSliceOfSlices(got), tt.want) { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestThreeSumTwoPointer(t *testing.T) { + for _, tt := range tests { + if got := ThreeSumTwoPointer(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func BenchmarkThreeSumBurst(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ThreeSumBurst(tests[0].arg1) + } +} + +func BenchmarkThreeSumDoublePoint(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ThreeSumDoublePoint(tests[0].arg1) + } +} + +func BenchmarkThreeSumHashTable(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ThreeSumHashTable(tests[0].arg1) + } +} + +func BenchmarkThreeSumTwoPointer(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ThreeSumTwoPointer(tests[0].arg1) + } +} + +/* +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0015.3Sum +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkThreeSumBurst-4 9838000 121.4 ns/op 48 B/op 2 allocs/op +BenchmarkThreeSumDoublePoint-4 9069201 112.8 ns/op 48 B/op 2 allocs/op +BenchmarkThreeSumHashTable-4 7935907 147.1 ns/op 48 B/op 2 allocs/op +BenchmarkThreeSumTwoPointer-4 10888315 103.5 ns/op 48 B/op 2 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0015.3Sum 5.055s +*/ diff --git a/Leetcode/0015.3Sum/index.html b/Leetcode/0015.3Sum/index.html new file mode 100644 index 000000000..fdfde0aba --- /dev/null +++ b/Leetcode/0015.3Sum/index.html @@ -0,0 +1,3951 @@ + + + + + + + 0015. 3Sum ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                            +
                                                                                                            + + + + + + + + +
                                                                                                            + +
                                                                                                            + +
                                                                                                            + + + + + + + + +
                                                                                                            +
                                                                                                            + +
                                                                                                            +
                                                                                                            + +
                                                                                                            + +

                                                                                                            15. 3Sum

                                                                                                            題目

                                                                                                            +

                                                                                                            Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

                                                                                                            +

                                                                                                            Note:

                                                                                                            +

                                                                                                            The solution set must not contain duplicate triplets.

                                                                                                            +

                                                                                                            Example:

                                                                                                            +
                                                                                                            Given array nums = [-1, 0, 1, 2, -1, -4],
                                                                                                            +
                                                                                                            +A solution set is:
                                                                                                            +[
                                                                                                            +  [-1, 0, 1],
                                                                                                            +  [-1, -1, 2]
                                                                                                            +]
                                                                                                            +
                                                                                                            +

                                                                                                            題目大意

                                                                                                            +

                                                                                                            給定一個數組,要求在這個數組中找出 3 個數之和為 0 的所有組合。

                                                                                                            +

                                                                                                            解題思路

                                                                                                            +

                                                                                                            用 map 提前計算好任意 2 個數字之和,保存起來,可以將時間複雜度降到 O(n^2)。這一題比較麻煩的一點在於,最後輸出解的時候,要求輸出不重複的解。數組中同一個數字可能出現多次,同一個數字也可能使用多次,但是最後輸出解的時候,不能重複。例如[-1,-1,2] 和[2, -1, -1]、[-1, 2, -1] 這3 個解是重複的,即使-1 可能出現100 次,每次使用的-1 的數組下標都是不同的。

                                                                                                            +

                                                                                                            這裡就需要去重和排序了。 map 記錄每個數字出現的次數,然後對 map 的 key 數組進行排序,最後在這個排序以後的數組裡面掃,找到另外 2 個數字能和自己組成 0 的組合。

                                                                                                            +

                                                                                                            來源

                                                                                                            + +

                                                                                                            解答

                                                                                                            +

                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0015.3Sum/3Sum.go

                                                                                                            +
                                                                                                            package threesum
                                                                                                            +
                                                                                                            +import (
                                                                                                            +    "sort"
                                                                                                            +)
                                                                                                            +
                                                                                                            +// ThreeSumBurst : 暴力解 : O(n^3)
                                                                                                            +func ThreeSumBurst(nums []int) [][]int {
                                                                                                            +    result := [][]int{}
                                                                                                            +    sort.Ints(nums) // O(n log n)
                                                                                                            +    for i := 0; i < len(nums); i++ {
                                                                                                            +        // 需要跟上一次不同
                                                                                                            +        if i > 0 && nums[i] == nums[i-1] {
                                                                                                            +            continue
                                                                                                            +        }
                                                                                                            +        for j := i + 1; j < len(nums); j++ {
                                                                                                            +            // 需要跟上一次不同
                                                                                                            +            if j > i+1 && nums[j] == nums[j-1] {
                                                                                                            +                continue
                                                                                                            +            }
                                                                                                            +            for k := j + 1; k < len(nums); k++ {
                                                                                                            +                if nums[i]+nums[j]+nums[k] == 0 {
                                                                                                            +                    result = append(result, []int{nums[i], nums[j], nums[k]})
                                                                                                            +                }
                                                                                                            +            }
                                                                                                            +        }
                                                                                                            +    }
                                                                                                            +    return result
                                                                                                            +}
                                                                                                            +
                                                                                                            +/*
                                                                                                            +ThreeSumDoublePoint : 最佳解, 排序 + 雙指針法 (滑動視窗) O(n^2)
                                                                                                            +1. 特判,對於數組長度 n,如果數組為 null 或者數組長度小於 3,返回 []。
                                                                                                            +2. 對數組進行排序。
                                                                                                            +3. 遍歷排序後數組:
                                                                                                            +  - 對於重複元素:跳過,避免出現重複解
                                                                                                            +  - 令左指針 L=i+1,右指針 R=n−1,當 L 1 && nums[i] == nums[i-1] {
                                                                                                            +            // 去掉重複
                                                                                                            +            start = i - 1
                                                                                                            +        }
                                                                                                            +        for start < i && end > i {
                                                                                                            +            if start > 0 && nums[start] == nums[start-1] {
                                                                                                            +                // 去掉重複
                                                                                                            +                start++
                                                                                                            +                continue
                                                                                                            +            }
                                                                                                            +            if end < (len(nums)-1) && nums[end] == nums[end+1] {
                                                                                                            +                // 去掉重複
                                                                                                            +                end--
                                                                                                            +                continue
                                                                                                            +            }
                                                                                                            +            addNum = nums[start] + nums[end] + nums[i]
                                                                                                            +            if addNum == 0 {
                                                                                                            +                result = append(result, []int{nums[start], nums[i], nums[end]})
                                                                                                            +                start++
                                                                                                            +                end--
                                                                                                            +            } else if addNum > 0 {
                                                                                                            +                end--
                                                                                                            +            } else {
                                                                                                            +                start++
                                                                                                            +            }
                                                                                                            +        }
                                                                                                            +    }
                                                                                                            +    return result
                                                                                                            +}
                                                                                                            +
                                                                                                            +func ThreeSumHashTable(nums []int) [][]int {
                                                                                                            +    result := [][]int{}
                                                                                                            +    if len(nums) < 3 {
                                                                                                            +        return result
                                                                                                            +    }
                                                                                                            +    sort.Ints(nums) // O(n log n)
                                                                                                            +
                                                                                                            +    for i := 0; i < len(nums)-2; i++ {
                                                                                                            +        // 避免重複的起始元素
                                                                                                            +        if i > 0 && nums[i] == nums[i-1] {
                                                                                                            +            continue
                                                                                                            +        }
                                                                                                            +
                                                                                                            +        seen := make(map[int]bool)
                                                                                                            +        target := -nums[i] // 目標值為當前元素的相反數
                                                                                                            +        for j := i + 1; j < len(nums); j++ {
                                                                                                            +            complement := target - nums[j] // 找到與當前元素配對的目標元素
                                                                                                            +            if seen[complement] {
                                                                                                            +                result = append(result, []int{nums[i], complement, nums[j]})
                                                                                                            +                // 避免重複的配對元素
                                                                                                            +                for j < len(nums)-1 && nums[j] == nums[j+1] {
                                                                                                            +                    j++
                                                                                                            +                }
                                                                                                            +            }
                                                                                                            +            seen[nums[j]] = true
                                                                                                            +        }
                                                                                                            +    }
                                                                                                            +    return result
                                                                                                            +}
                                                                                                            +
                                                                                                            +func ThreeSumTwoPointer(nums []int) [][]int {
                                                                                                            +    result := [][]int{}
                                                                                                            +    sort.Ints(nums)
                                                                                                            +
                                                                                                            +    for i := 0; i < len(nums)-2; i++ {
                                                                                                            +        if i > 0 && nums[i] == nums[i-1] {
                                                                                                            +            continue
                                                                                                            +        }
                                                                                                            +        target, l, r := -nums[i], i+1, len(nums)-1
                                                                                                            +        for l < r {
                                                                                                            +            sum := nums[l] + nums[r]
                                                                                                            +            if sum == target {
                                                                                                            +                result = append(result, []int{nums[i], nums[l], nums[r]})
                                                                                                            +                l++
                                                                                                            +                r--
                                                                                                            +                for l < r && nums[l] == nums[l-1] {
                                                                                                            +                    l++
                                                                                                            +                }
                                                                                                            +                for l < r && nums[r] == nums[r+1] {
                                                                                                            +                    r--
                                                                                                            +                }
                                                                                                            +            } else if sum > target {
                                                                                                            +                r--
                                                                                                            +            } else if sum < target {
                                                                                                            +                l++
                                                                                                            +            }
                                                                                                            +        }
                                                                                                            +    }
                                                                                                            +    return result
                                                                                                            +}
                                                                                                            +
                                                                                                            +
                                                                                                            goos: darwin
                                                                                                            +goarch: amd64
                                                                                                            +pkg: LeetcodeGolang/Leetcode/0015.3Sum
                                                                                                            +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
                                                                                                            +BenchmarkThreeSumBurst-4                 9838000               121.4 ns/op            48 B/op          2 allocs/op
                                                                                                            +BenchmarkThreeSumDoublePoint-4           9069201               112.8 ns/op            48 B/op          2 allocs/op
                                                                                                            +BenchmarkThreeSumHashTable-4             7935907               147.1 ns/op            48 B/op          2 allocs/op
                                                                                                            +BenchmarkThreeSumTwoPointer-4           10888315               103.5 ns/op            48 B/op          2 allocs/op
                                                                                                            +PASS
                                                                                                            +ok      LeetcodeGolang/Leetcode/0015.3Sum       5.055s
                                                                                                            +
                                                                                                            +
                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                            + +
                                                                                                            + +
                                                                                                            +
                                                                                                            +
                                                                                                            + +

                                                                                                            results matching ""

                                                                                                            +
                                                                                                              + +
                                                                                                              +
                                                                                                              + +

                                                                                                              No results matching ""

                                                                                                              + +
                                                                                                              +
                                                                                                              +
                                                                                                              + +
                                                                                                              +
                                                                                                              + +
                                                                                                              + + + + + + +
                                                                                                              + + +
                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0019.Remove-Nth-Node-From-End-of-List/index.html b/Leetcode/0019.Remove-Nth-Node-From-End-of-List/index.html new file mode 100644 index 000000000..440c1089a --- /dev/null +++ b/Leetcode/0019.Remove-Nth-Node-From-End-of-List/index.html @@ -0,0 +1,3844 @@ + + + + + + + 0019. Remove Nth Node From End of List ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                              +
                                                                                                              + + + + + + + + +
                                                                                                              + +
                                                                                                              + +
                                                                                                              + + + + + + + + +
                                                                                                              +
                                                                                                              + +
                                                                                                              +
                                                                                                              + +
                                                                                                              + +

                                                                                                              19. Remove Nth Node From End of List

                                                                                                              題目

                                                                                                              +

                                                                                                              Given the head of a linked list, remove the nth node from the end of the list and return its head.

                                                                                                              +

                                                                                                              Example 1: +

                                                                                                              +
                                                                                                              Input: head = [1,2,3,4,5], n = 2
                                                                                                              +Output: [1,2,3,5]
                                                                                                              +

                                                                                                              Example 2:

                                                                                                              +
                                                                                                              Input: head = [1], n = 1
                                                                                                              +Output: []
                                                                                                              +

                                                                                                              Example 3:

                                                                                                              +
                                                                                                              Input: head = [1,2], n = 1
                                                                                                              +Output: [1]
                                                                                                              +

                                                                                                              Constraints:

                                                                                                              +
                                                                                                                +
                                                                                                              • The number of nodes in the list is sz.
                                                                                                              • +
                                                                                                              • 1 <= sz <= 30
                                                                                                              • +
                                                                                                              • 0 <= Node.val <= 100
                                                                                                              • +
                                                                                                              • 1 <= n <= sz
                                                                                                              • +
                                                                                                              +

                                                                                                              題目大意

                                                                                                              +

                                                                                                              找尋單linked list的 倒數第 n 個元素並刪除. +返回該 linked list的頭節點

                                                                                                              +

                                                                                                              解題思路

                                                                                                              +

                                                                                                              先讓 fast走 k 步, 然後 fast slow 同速前進 +這樣當fast走到nil時, slow所在位置就是在倒數第 k 的節點

                                                                                                              +

                                                                                                              來源

                                                                                                              + +

                                                                                                              解答

                                                                                                              +

                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main.go

                                                                                                              +
                                                                                                              package removenthnodefromendoflist
                                                                                                              +
                                                                                                              +/**
                                                                                                              + * Definition for singly-linked list.
                                                                                                              + * type ListNode struct {
                                                                                                              + *     Val int
                                                                                                              + *     Next *ListNode
                                                                                                              + * }
                                                                                                              + */
                                                                                                              +
                                                                                                              +type ListNode struct {
                                                                                                              +    Val  int
                                                                                                              +    Next *ListNode
                                                                                                              +}
                                                                                                              +
                                                                                                              +// 產生 dummyHead,跟 preslow
                                                                                                              +// 使用雙指針, 先讓 fast走 `k` 步, 然後 `fast slow 同速前進`
                                                                                                              +// 這樣當fast走到nil時, slow所在位置就是在倒數第 k 的節點
                                                                                                              +// 將 slow的前一步(preslow)的next 指向 slow.Next
                                                                                                              +func RemoveNthFromEnd(head *ListNode, n int) *ListNode {
                                                                                                              +    dummyHead := &ListNode{Next: head}
                                                                                                              +    preSlow, slow, fast := dummyHead, head, head
                                                                                                              +    for fast != nil {
                                                                                                              +        if n 
                                                                                                              +
                                                                                                              tags: Medium Leetcode Two Pointers
                                                                                                              +
                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                              + +
                                                                                                              + +
                                                                                                              +
                                                                                                              +
                                                                                                              + +

                                                                                                              results matching ""

                                                                                                              +
                                                                                                                + +
                                                                                                                +
                                                                                                                + +

                                                                                                                No results matching ""

                                                                                                                + +
                                                                                                                +
                                                                                                                +
                                                                                                                + +
                                                                                                                +
                                                                                                                + +
                                                                                                                + + + + + + +
                                                                                                                + + +
                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main.go b/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main.go new file mode 100644 index 000000000..65fef229e --- /dev/null +++ b/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main.go @@ -0,0 +1,35 @@ +package removenthnodefromendoflist + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + +type ListNode struct { + Val int + Next *ListNode +} + +// ็”ข็”Ÿ dummyHead,่ทŸ preslow +// ไฝฟ็”จ้›™ๆŒ‡้‡, ๅ…ˆ่ฎ“ fast่ตฐ `k` ๆญฅ, ็„ถๅพŒ `fast slow ๅŒ้€Ÿๅ‰้€ฒ` +// ้€™ๆจฃ็•ถfast่ตฐๅˆฐnilๆ™‚, slowๆ‰€ๅœจไฝ็ฝฎๅฐฑๆ˜ฏๅœจๅ€’ๆ•ธ็ฌฌ k ็š„็ฏ€้ปž +// ๅฐ‡ slow็š„ๅ‰ไธ€ๆญฅ(preslow)็š„next ๆŒ‡ๅ‘ slow.Next +func RemoveNthFromEnd(head *ListNode, n int) *ListNode { + dummyHead := &ListNode{Next: head} + preSlow, slow, fast := dummyHead, head, head + for fast != nil { + if n <= 0 { + // ๅ…ˆ่ฎ“ fast่ตฐ `k` ๆญฅ, ็„ถๅพŒ `fast slow ๅŒ้€Ÿๅ‰้€ฒ` + // ้€™ๆจฃ็•ถfast่ตฐๅˆฐnilๆ™‚, slowๆ‰€ๅœจไฝ็ฝฎๅฐฑๆ˜ฏๅœจๅ€’ๆ•ธ็ฌฌ k ็š„็ฏ€้ปž + preSlow = slow + slow = slow.Next + } + n-- + fast = fast.Next + } + preSlow.Next = slow.Next + return dummyHead.Next +} diff --git a/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main_test.go b/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main_test.go new file mode 100644 index 000000000..3e306a9b1 --- /dev/null +++ b/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main_test.go @@ -0,0 +1,45 @@ +package removenthnodefromendoflist + +import ( + "reflect" + "testing" +) + +func TestRemoveNthFromEnd(t *testing.T) { + a := &ListNode{1, nil} + b := &ListNode{2, nil} + c := &ListNode{3, nil} + d := &ListNode{4, nil} + e := &ListNode{5, nil} + + a.Next = b + b.Next = c + c.Next = d + d.Next = e + e.Next = nil + + tests := []struct { + arg1 *ListNode + arg2 int + want []int + }{ + { + arg1: a, + arg2: 2, + want: []int{1, 2, 3, 5}, + }, + } + + for _, tt := range tests { + got := RemoveNthFromEnd(tt.arg1, tt.arg2) + + gotArr := []int{} + for got != nil { + gotArr = append(gotArr, got.Val) + got = got.Next + } + if !reflect.DeepEqual(gotArr, tt.want) { + t.Errorf("got = %v, want = %v", gotArr, tt.want) + } + } +} diff --git a/Leetcode/0020.Valid-Parentheses/index.html b/Leetcode/0020.Valid-Parentheses/index.html new file mode 100644 index 000000000..c4a7c63d5 --- /dev/null +++ b/Leetcode/0020.Valid-Parentheses/index.html @@ -0,0 +1,3857 @@ + + + + + + + 0020. Valid Parentheses ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                +
                                                                                                                + + + + + + + + +
                                                                                                                + +
                                                                                                                + +
                                                                                                                + + + + + + + + +
                                                                                                                +
                                                                                                                + +
                                                                                                                +
                                                                                                                + +
                                                                                                                + +

                                                                                                                0020. Valid Parentheses

                                                                                                                題目

                                                                                                                +

                                                                                                                Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

                                                                                                                +

                                                                                                                An input string is valid if:

                                                                                                                +

                                                                                                                Open brackets must be closed by the same type of brackets. +Open brackets must be closed in the correct order. +Every close bracket has a corresponding open bracket of the same type.

                                                                                                                +

                                                                                                                Example 1:

                                                                                                                +

                                                                                                                Input: s = "()" +Output: true +Example 2:

                                                                                                                +

                                                                                                                Input: s = "()[]{}" +Output: true +Example 3:

                                                                                                                +

                                                                                                                Input: s = "(]" +Output: false

                                                                                                                +

                                                                                                                Constraints:

                                                                                                                +

                                                                                                                1 <= s.length <= 104 +s consists of parentheses only '()[]{}'.

                                                                                                                +

                                                                                                                題目大意

                                                                                                                +

                                                                                                                解題思路

                                                                                                                +

                                                                                                                Big O

                                                                                                                +

                                                                                                                時間複雜 : 空間複雜 :

                                                                                                                +

                                                                                                                來源

                                                                                                                + +

                                                                                                                解答

                                                                                                                +

                                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0020.Valid-Parentheses/main.go

                                                                                                                +
                                                                                                                package validparentheses
                                                                                                                +
                                                                                                                +type Stack struct {
                                                                                                                +    runes []rune
                                                                                                                +}
                                                                                                                +
                                                                                                                +func NewStack() *Stack {
                                                                                                                +    return &Stack{runes: []rune{}}
                                                                                                                +}
                                                                                                                +
                                                                                                                +func (s *Stack) Push(str rune) {
                                                                                                                +    s.runes = append(s.runes, str)
                                                                                                                +}
                                                                                                                +
                                                                                                                +func (s *Stack) Pop() rune {
                                                                                                                +    str := s.runes[len(s.runes)-1]
                                                                                                                +    s.runes = s.runes[:len(s.runes)-1]
                                                                                                                +    return str
                                                                                                                +}
                                                                                                                +
                                                                                                                +// 時間複雜 O(n), 空間複雜 O(n)
                                                                                                                +func IsValid(s string) bool {
                                                                                                                +    runeStack := NewStack()
                                                                                                                +    for _, v := range s {
                                                                                                                +        // fmt.Println(string(v))
                                                                                                                +        if v == '(' || v == '[' || v == '{' {
                                                                                                                +            runeStack.Push(v)
                                                                                                                +        } else if (v == ')' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '(') || (v == ']' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '[') || (v == '}' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '{') {
                                                                                                                +            runeStack.Pop()
                                                                                                                +        } else {
                                                                                                                +            return false
                                                                                                                +        }
                                                                                                                +    }
                                                                                                                +    return len(runeStack.runes) == 0
                                                                                                                +}
                                                                                                                +
                                                                                                                +

                                                                                                                Benchmark

                                                                                                                +
                                                                                                                
                                                                                                                +
                                                                                                                +
                                                                                                                +
                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                + +
                                                                                                                + +
                                                                                                                +
                                                                                                                +
                                                                                                                + +

                                                                                                                results matching ""

                                                                                                                +
                                                                                                                  + +
                                                                                                                  +
                                                                                                                  + +

                                                                                                                  No results matching ""

                                                                                                                  + +
                                                                                                                  +
                                                                                                                  +
                                                                                                                  + +
                                                                                                                  +
                                                                                                                  + +
                                                                                                                  + + + + + + +
                                                                                                                  + + +
                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0020.Valid-Parentheses/main.go b/Leetcode/0020.Valid-Parentheses/main.go new file mode 100644 index 000000000..4a51f1b86 --- /dev/null +++ b/Leetcode/0020.Valid-Parentheses/main.go @@ -0,0 +1,35 @@ +package validparentheses + +type Stack struct { + runes []rune +} + +func NewStack() *Stack { + return &Stack{runes: []rune{}} +} + +func (s *Stack) Push(str rune) { + s.runes = append(s.runes, str) +} + +func (s *Stack) Pop() rune { + str := s.runes[len(s.runes)-1] + s.runes = s.runes[:len(s.runes)-1] + return str +} + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(n) +func IsValid(s string) bool { + runeStack := NewStack() + for _, v := range s { + // fmt.Println(string(v)) + if v == '(' || v == '[' || v == '{' { + runeStack.Push(v) + } else if (v == ')' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '(') || (v == ']' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '[') || (v == '}' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '{') { + runeStack.Pop() + } else { + return false + } + } + return len(runeStack.runes) == 0 +} diff --git a/Leetcode/0020.Valid-Parentheses/main_test.go b/Leetcode/0020.Valid-Parentheses/main_test.go new file mode 100644 index 000000000..3e8261805 --- /dev/null +++ b/Leetcode/0020.Valid-Parentheses/main_test.go @@ -0,0 +1,46 @@ +package validparentheses + +import "testing" + +var tests = []struct { + arg1 string + want bool +}{ + { + "()", + true, + }, + { + "()[]{}", + true, + }, + { + "(]", + false, + }, + { + "[", + false, + }, +} + +func TestIsValid(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := IsValid(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkIsValid(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + IsValid(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0021.Merge-Two-Sorted-Lists/index.html b/Leetcode/0021.Merge-Two-Sorted-Lists/index.html new file mode 100644 index 000000000..132b0747a --- /dev/null +++ b/Leetcode/0021.Merge-Two-Sorted-Lists/index.html @@ -0,0 +1,3837 @@ + + + + + + + 0021. Merge Two Sorted Lists ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                  +
                                                                                                                  + + + + + + + + +
                                                                                                                  + +
                                                                                                                  + +
                                                                                                                  + + + + + + + + +
                                                                                                                  +
                                                                                                                  + +
                                                                                                                  +
                                                                                                                  + +
                                                                                                                  + +

                                                                                                                  0021. Merge Two Sorted Lists

                                                                                                                  題目

                                                                                                                  +

                                                                                                                  題目大意

                                                                                                                  +

                                                                                                                  解題思路

                                                                                                                  +

                                                                                                                  Big O

                                                                                                                  +

                                                                                                                  時間複雜 : O( log n) +空間複雜 : O(1)

                                                                                                                  +

                                                                                                                  來源

                                                                                                                  + +

                                                                                                                  解答

                                                                                                                  +

                                                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0021.Merge-Two-Sorted-Lists/main.go

                                                                                                                  +
                                                                                                                  package mergetwosortedlists
                                                                                                                  +
                                                                                                                  +type ListNode struct {
                                                                                                                  +    Val  int
                                                                                                                  +    Next *ListNode
                                                                                                                  +}
                                                                                                                  +
                                                                                                                  +// 時間複雜 O(log n), 空間複雜 O(1)
                                                                                                                  +func MergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
                                                                                                                  +    head := &ListNode{Next: nil}
                                                                                                                  +    cur := head
                                                                                                                  +
                                                                                                                  +    for list1 != nil && list2 != nil {
                                                                                                                  +        if list1.Val < list2.Val {
                                                                                                                  +            cur.Next = list1
                                                                                                                  +            list1 = list1.Next
                                                                                                                  +        } else {
                                                                                                                  +            cur.Next = list2
                                                                                                                  +            list2 = list2.Next
                                                                                                                  +        }
                                                                                                                  +        cur = cur.Next
                                                                                                                  +    }
                                                                                                                  +
                                                                                                                  +    if list1 != nil {
                                                                                                                  +        cur.Next = list1
                                                                                                                  +    }
                                                                                                                  +    if list2 != nil {
                                                                                                                  +        cur.Next = list2
                                                                                                                  +    }
                                                                                                                  +    return head.Next
                                                                                                                  +}
                                                                                                                  +
                                                                                                                  +

                                                                                                                  Benchmark

                                                                                                                  +
                                                                                                                  
                                                                                                                  +
                                                                                                                  +
                                                                                                                  +
                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                  + +
                                                                                                                  + +
                                                                                                                  +
                                                                                                                  +
                                                                                                                  + +

                                                                                                                  results matching ""

                                                                                                                  +
                                                                                                                    + +
                                                                                                                    +
                                                                                                                    + +

                                                                                                                    No results matching ""

                                                                                                                    + +
                                                                                                                    +
                                                                                                                    +
                                                                                                                    + +
                                                                                                                    +
                                                                                                                    + +
                                                                                                                    + + + + + + +
                                                                                                                    + + +
                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0021.Merge-Two-Sorted-Lists/main.go b/Leetcode/0021.Merge-Two-Sorted-Lists/main.go new file mode 100644 index 000000000..1d367cb86 --- /dev/null +++ b/Leetcode/0021.Merge-Two-Sorted-Lists/main.go @@ -0,0 +1,31 @@ +package mergetwosortedlists + +type ListNode struct { + Val int + Next *ListNode +} + +// ๆ™‚้–“่ค‡้›œ O(log n), ็ฉบ้–“่ค‡้›œ O(1) +func MergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { + head := &ListNode{Next: nil} + cur := head + + for list1 != nil && list2 != nil { + if list1.Val < list2.Val { + cur.Next = list1 + list1 = list1.Next + } else { + cur.Next = list2 + list2 = list2.Next + } + cur = cur.Next + } + + if list1 != nil { + cur.Next = list1 + } + if list2 != nil { + cur.Next = list2 + } + return head.Next +} diff --git a/Leetcode/0021.Merge-Two-Sorted-Lists/main_test.go b/Leetcode/0021.Merge-Two-Sorted-Lists/main_test.go new file mode 100644 index 000000000..816ad9c46 --- /dev/null +++ b/Leetcode/0021.Merge-Two-Sorted-Lists/main_test.go @@ -0,0 +1,78 @@ +package mergetwosortedlists + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + arg2 []int + want []int +}{ + { + []int{1, 2, 4}, + []int{1, 3, 4}, + []int{1, 1, 2, 3, 4, 4}, + }, +} + +func TestMergeTwoLists(t *testing.T) { + for _, tt := range tests { + arg1 := &ListNode{} + arg1Cur := arg1 + for _, v := range tt.arg1 { + tmp := &ListNode{Val: v} + arg1Cur.Next = tmp + arg1Cur = arg1Cur.Next + } + + arg2 := &ListNode{} + arg2Cur := arg2 + for _, v := range tt.arg2 { + tmp := &ListNode{Val: v} + arg2Cur.Next = tmp + arg2Cur = arg2Cur.Next + } + + wantNode := &ListNode{} + wantNodeCur := wantNode + for _, v := range tt.want { + tmp := &ListNode{Val: v} + wantNodeCur.Next = tmp + wantNodeCur = wantNodeCur.Next + } + + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MergeTwoLists(arg1.Next, arg2.Next); !reflect.DeepEqual(got, wantNode.Next) { + t.Errorf("got = %v, want = %v", got, wantNode.Next) + } + } +} + +func BenchmarkMergeTwoLists(b *testing.B) { + b.ResetTimer() + arg1 := &ListNode{} + arg1Cur := arg1 + for _, v := range tests[0].arg1 { + tmp := &ListNode{Val: v} + arg1Cur.Next = tmp + arg1Cur = arg1Cur.Next + } + + arg2 := &ListNode{} + arg2Cur := arg2 + for _, v := range tests[0].arg2 { + tmp := &ListNode{Val: v} + arg2Cur.Next = tmp + arg2Cur = arg2Cur.Next + } + for i := 0; i < b.N; i++ { + MergeTwoLists(arg1.Next, arg2.Next) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0027.Remove-Element/Remove-Element.go b/Leetcode/0027.Remove-Element/Remove-Element.go new file mode 100644 index 000000000..b8fd61b5e --- /dev/null +++ b/Leetcode/0027.Remove-Element/Remove-Element.go @@ -0,0 +1,39 @@ +package removeelement + +/* +้›™ๆŒ‡้‡ๆณ• +้›™ๆŒ‡้‡ๆณ•๏ผˆๅฟซๆ…ขๆŒ‡้‡ๆณ•๏ผ‰ๅœจๆ•ธ็ต„ๅ’Œ้Š้Œถ็š„ๆ“ไฝœไธญๆ˜ฏ้žๅธธๅธธ่ฆ‹็š„๏ผŒๅพˆๅคš่€ƒๅฏŸๆ•ธ็ต„ๅ’Œ้Š้Œถๆ“ไฝœ็š„้ข่ฉฆ้กŒ๏ผŒ้ƒฝไฝฟ็”จ้›™ๆŒ‡้‡ๆณ• +*/ +func RemoveElementDoublePoint(nums []int, val int) int { + if len(nums) <= 0 { + return 0 + } + slowIndex := 0 + for fastIndex := 0; fastIndex < len(nums); fastIndex++ { + if nums[fastIndex] != val { + if fastIndex != slowIndex { + nums[fastIndex], nums[slowIndex] = nums[slowIndex], nums[fastIndex] + } + slowIndex++ + } + } + return slowIndex +} + +/* +RemoveElement : +*/ +func RemoveElement(nums []int, val int) int { + size := len(nums) + i := 0 + for i < size { + if nums[i] == val { + nums = append(nums[:i], nums[i+1:]...) + size-- + // fmt.Println(nums) + } else { + i++ + } + } + return len(nums) +} diff --git a/Leetcode/0027.Remove-Element/Remove-Element_test.go b/Leetcode/0027.Remove-Element/Remove-Element_test.go new file mode 100644 index 000000000..f30f75b0f --- /dev/null +++ b/Leetcode/0027.Remove-Element/Remove-Element_test.go @@ -0,0 +1,79 @@ +package removeelement + +import ( + "testing" +) + +var tests = []struct { + arg1 []int + arg2 int + want int +}{ + { + []int{1, 0, 1}, + 1, + 1, + }, + { + []int{0, 1, 0, 3, 0, 12}, + 0, + 3, + }, + { + []int{0, 1, 0, 3, 0, 0, 0, 0, 1, 12}, + 0, + 4, + }, + { + []int{0, 0, 0, 0, 0}, + 0, + 0, + }, + + { + []int{1}, + 1, + 0, + }, + { + []int{0, 1, 2, 2, 3, 0, 4, 2}, + 2, + 5, + }, +} + +func TestRemoveElementDoublePoint(t *testing.T) { + for _, tt := range tests { + if got := RemoveElementDoublePoint(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestRemoveElement(t *testing.T) { + for _, tt := range tests { + if got := RemoveElement(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func BenchmarkRemoveElement(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + RemoveElement(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkRemoveElementDoublePoint(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + RemoveElementDoublePoint(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0027.Remove-Element -bench=. +BenchmarkRemoveElement-8 100000000 10.66 ns/op 0 B/op 0 allocs/op +BenchmarkRemoveElementDoublePoint-8 285200671 5.456 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Leetcode/0027.Remove-Element/index.html b/Leetcode/0027.Remove-Element/index.html new file mode 100644 index 000000000..d4eb995a0 --- /dev/null +++ b/Leetcode/0027.Remove-Element/index.html @@ -0,0 +1,3842 @@ + + + + + + + 0027.Remove Element ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                    +
                                                                                                                    + + + + + + + + +
                                                                                                                    + +
                                                                                                                    + +
                                                                                                                    + + + + + + + + +
                                                                                                                    +
                                                                                                                    + +
                                                                                                                    +
                                                                                                                    + +
                                                                                                                    + +

                                                                                                                    27. Remove Element

                                                                                                                    題目

                                                                                                                    +

                                                                                                                    Given an array nums and a value val, remove all instances of that value in-place and return the new length.

                                                                                                                    +

                                                                                                                    Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

                                                                                                                    +

                                                                                                                    The order of elements can be changed. It doesn't matter what you leave beyond the new length.

                                                                                                                    +

                                                                                                                    Example 1:

                                                                                                                    +
                                                                                                                    Given nums = [3,2,2,3], val = 3,
                                                                                                                    +
                                                                                                                    +Your function should return length = 2, with the first two elements of nums being 2.
                                                                                                                    +
                                                                                                                    +It doesn't matter what you leave beyond the returned length.
                                                                                                                    +
                                                                                                                    +

                                                                                                                    Example 2:

                                                                                                                    +
                                                                                                                    Given nums = [0,1,2,2,3,0,4,2], val = 2,
                                                                                                                    +
                                                                                                                    +Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
                                                                                                                    +
                                                                                                                    +Note that the order of those five elements can be arbitrary.
                                                                                                                    +
                                                                                                                    +It doesn't matter what values are set beyond the returned length.
                                                                                                                    +
                                                                                                                    +

                                                                                                                    Clarification:

                                                                                                                    +

                                                                                                                    Confused why the returned value is an integer but your answer is an array?

                                                                                                                    +

                                                                                                                    Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.

                                                                                                                    +

                                                                                                                    Internally you can think of this:

                                                                                                                    +
                                                                                                                    // nums is passed in by reference. (i.e., without making a copy)
                                                                                                                    +int len = removeElement(nums, val);
                                                                                                                    +
                                                                                                                    +// any modification to nums in your function would be known by the caller.
                                                                                                                    +// using the length returned by your function, it prints the first len elements.
                                                                                                                    +for (int i = 0; i < len; i++) {
                                                                                                                    +    print(nums[i]);
                                                                                                                    +}
                                                                                                                    +
                                                                                                                    +

                                                                                                                    題目大意

                                                                                                                    +

                                                                                                                    給定一個數組 nums 和一個數值 val,將數組中所有等於 val 的元素刪除,並返回剩餘的元素個數。

                                                                                                                    +

                                                                                                                    解題思路

                                                                                                                    +

                                                                                                                    這道題和第 283 題很像。這道題和第 283 題基本一致,283 題是刪除 0,這一題是給定的一個 val,實質是一樣的。

                                                                                                                    +

                                                                                                                    這里數組的刪除並不是真的刪除,只是將刪除的元素移動到數組後面的空間內,然後返回數組實際剩餘的元素個數,OJ 最終判斷題目的時候會讀取數組剩餘個數的元素進行輸出。

                                                                                                                    +

                                                                                                                    來源

                                                                                                                    + +

                                                                                                                    解答

                                                                                                                    +

                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0027.Remove-Element/Remove-Element.go

                                                                                                                    +
                                                                                                                    package removeelement
                                                                                                                    +
                                                                                                                    +/*
                                                                                                                    +雙指針法
                                                                                                                    +雙指針法(快慢指針法)在數組和鍊錶的操作中是非常常見的,很多考察數組和鍊錶操作的面試題,都使用雙指針法
                                                                                                                    +*/
                                                                                                                    +func RemoveElementDoublePoint(nums []int, val int) int {
                                                                                                                    +    if len(nums) 
                                                                                                                    +
                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                    + +
                                                                                                                    + +
                                                                                                                    +
                                                                                                                    +
                                                                                                                    + +

                                                                                                                    results matching ""

                                                                                                                    +
                                                                                                                      + +
                                                                                                                      +
                                                                                                                      + +

                                                                                                                      No results matching ""

                                                                                                                      + +
                                                                                                                      +
                                                                                                                      +
                                                                                                                      + +
                                                                                                                      +
                                                                                                                      + +
                                                                                                                      + + + + + + +
                                                                                                                      + + +
                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/index.html b/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/index.html new file mode 100644 index 000000000..3470b79e4 --- /dev/null +++ b/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/index.html @@ -0,0 +1,3810 @@ + + + + + + + 0028. Find the Index of the First Occurrence in a String ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                      +
                                                                                                                      + + + + + + + + +
                                                                                                                      + +
                                                                                                                      + +
                                                                                                                      + + + + + + + + +
                                                                                                                      +
                                                                                                                      + +
                                                                                                                      + +
                                                                                                                      +
                                                                                                                      + +

                                                                                                                      results matching ""

                                                                                                                      +
                                                                                                                        + +
                                                                                                                        +
                                                                                                                        + +

                                                                                                                        No results matching ""

                                                                                                                        + +
                                                                                                                        +
                                                                                                                        +
                                                                                                                        + +
                                                                                                                        +
                                                                                                                        + +
                                                                                                                        + + + + + + +
                                                                                                                        + + +
                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main.go b/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main.go new file mode 100644 index 000000000..38ad805b0 --- /dev/null +++ b/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main.go @@ -0,0 +1,41 @@ +package findtheindexofthefirstoccurrenceinastring + +// ๆšดๅŠ›่งฃ +// ๆ™‚้–“่ค‡้›œ O(M*N), ็ฉบ้–“่ค‡้›œ O() +func strStr(haystack string, needle string) int { + haystackLen := len(haystack) + needleLen := len(needle) + index := 0 + for i := 0; i <= (haystackLen - needleLen); i++ { + j := 0 + for j = 0; j < needleLen; j++ { + if haystack[i+j] == needle[j] { + index = i + } else { + break + } + } + if j == needleLen { + return index + } + } + return -1 +} + +// Slice ่งฃๆณ• +func strStrSlice(haystack string, needle string) int { + haystackLen := len(haystack) + needleLen := len(needle) + if haystackLen == 0 || haystackLen < needleLen { + return -1 + } + if needleLen == 0 { + return 0 + } + for i := 0; i <= (haystackLen - needleLen); i++ { + if haystack[i:i+needleLen] == needle { + return i + } + } + return -1 +} diff --git a/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main_test.go b/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main_test.go new file mode 100644 index 000000000..0788b7309 --- /dev/null +++ b/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main_test.go @@ -0,0 +1,34 @@ +package + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "bbbab", + 4, + }, +} + +func TestLongestPalindromeSubseq(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := LongestPalindromeSubseq(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubseq(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindromeSubseq(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0035.Search-Insert-Position/Search-Insert-Position.go b/Leetcode/0035.Search-Insert-Position/Search-Insert-Position.go new file mode 100644 index 000000000..67f5f1653 --- /dev/null +++ b/Leetcode/0035.Search-Insert-Position/Search-Insert-Position.go @@ -0,0 +1,48 @@ +package searchinsertposition + +// ๆšดๅŠ›่งฃ ๆ™‚้–“่ค‡้›œ O(n) ็ฉบ้–“่ค‡้›œ O(1) +func SearchInsertBurst(nums []int, target int) int { + for i := 0; i < len(nums); i++ { + if nums[i] >= target { + return i + } + } + return len(nums) +} + +//ไบŒๅˆ†ๆณ• ๆ™‚้–“่ค‡้›œ O(log n) ็ฉบ้–“่ค‡้›œ O(1) +func SearchInsertBisection(nums []int, target int) int { + left, right := 0, len(nums)-1 + for left <= right { + // / ้˜ฒๆญขๆบขๅ‡บ ๅŒ(left + right)/2 + mid := left + (right-left)>>1 + if nums[mid] >= target { + right = mid - 1 + } else if nums[mid] < target { + left = mid + 1 + } else { + return mid + } + } + // ๅˆ†ๅˆฅ่™•็†ๅฆ‚ไธ‹ๅ››็จฎๆƒ…ๆณ + // targeๅœจๆ‰€ๆœ‰ๅ…ƒ็ด ไน‹ๅ‰ [0, -1] + // targe็ญ‰ๆ–ผๆ•ธ็ต„ไธญๆŸไธ€ๅ€‹ๅ…ƒ็ด  return middle; + // targeๅœจๆ•ธ็ต„ไธญ็š„ไฝ็ฝฎ [left, right]๏ผŒreturn right + 1 + // targeๅœจๆ•ธ็ต„ๆ‰€ๆœ‰ๅ…ƒ็ด ไน‹ๅพŒ็š„ๆƒ…ๆณ [left, right]๏ผŒ return right + 1 + return right + 1 +} + +//ไบŒๅˆ†ๆณ• ๆ™‚้–“่ค‡้›œ O(log n) ็ฉบ้–“่ค‡้›œ O(1) +func SearchInsertBisection2(nums []int, target int) int { + left, right := 0, len(nums)-1 + for left <= right { + // / ้˜ฒๆญขๆบขๅ‡บ ๅŒ(left + right)/2 + mid := left + (right-left)>>1 + if nums[mid] >= target { + right = mid - 1 + } else { + left = mid + 1 + } + } + return left +} diff --git a/Leetcode/0035.Search-Insert-Position/Search-Insert-Position_test.go b/Leetcode/0035.Search-Insert-Position/Search-Insert-Position_test.go new file mode 100644 index 000000000..0c08cbcc4 --- /dev/null +++ b/Leetcode/0035.Search-Insert-Position/Search-Insert-Position_test.go @@ -0,0 +1,83 @@ +package searchinsertposition + +import "testing" + +var tests = []struct { + arg1 []int + arg2 int + want int +}{ + { + arg1: []int{1, 3, 5, 6}, + arg2: 5, + want: 2, + }, + { + arg1: []int{1, 3, 5, 6}, + arg2: 2, + want: 1, + }, + { + arg1: []int{1, 3, 5, 6}, + arg2: 7, + want: 4, + }, + { + arg1: []int{1, 3, 5, 6}, + arg2: 0, + want: 0, + }, +} + +func TestSearchInsertBurst(t *testing.T) { + for _, tt := range tests { + if got := SearchInsertBurst(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSearchInsertBisection(t *testing.T) { + for _, tt := range tests { + if got := SearchInsertBisection(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSearchInsertBisection2(t *testing.T) { + for _, tt := range tests { + if got := SearchInsertBisection2(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSearchInsertBurst(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + SearchInsertBurst(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkSearchInsertBisection(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + SearchInsertBisection(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkSearchInsertBisection2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + SearchInsertBisection2(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0035.Search-Insert-Position -bench=. +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkSearchInsertBurst-8 742931880 1.891 ns/op 0 B/op 0 allocs/op +BenchmarkSearchInsertBisection-8 328495410 3.576 ns/op 0 B/op 0 allocs/op +BenchmarkSearchInsertBisection2-8 470675948 2.811 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Leetcode/0035.Search-Insert-Position/index.html b/Leetcode/0035.Search-Insert-Position/index.html new file mode 100644 index 000000000..24b6cc59c --- /dev/null +++ b/Leetcode/0035.Search-Insert-Position/index.html @@ -0,0 +1,3871 @@ + + + + + + + 0035.Search Insert Position ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                        +
                                                                                                                        + + + + + + + + +
                                                                                                                        + +
                                                                                                                        + +
                                                                                                                        + + + + + + + + +
                                                                                                                        +
                                                                                                                        + +
                                                                                                                        +
                                                                                                                        + +
                                                                                                                        + +

                                                                                                                        35. Search Insert Position

                                                                                                                        題目

                                                                                                                        +

                                                                                                                        Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

                                                                                                                        +

                                                                                                                        You may assume no duplicates in the array.

                                                                                                                        +

                                                                                                                        Example 1:

                                                                                                                        +
                                                                                                                        Input: [1,3,5,6], 5
                                                                                                                        +Output: 2
                                                                                                                        +

                                                                                                                        Example 2:

                                                                                                                        +
                                                                                                                        Input: [1,3,5,6], 2
                                                                                                                        +Output: 1
                                                                                                                        +

                                                                                                                        Example 3:

                                                                                                                        +
                                                                                                                        Input: [1,3,5,6], 7
                                                                                                                        +Output: 4
                                                                                                                        +

                                                                                                                        Example 4:

                                                                                                                        +
                                                                                                                        Input: [1,3,5,6], 0
                                                                                                                        +Output: 0
                                                                                                                        +

                                                                                                                        題目大意

                                                                                                                        +

                                                                                                                        給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。如果目標值不存在於數組中,返回它將會被按順序插入的位置。

                                                                                                                        +

                                                                                                                        你可以假設數組中無重複元素。

                                                                                                                        +

                                                                                                                        解題思路

                                                                                                                        +
                                                                                                                          +
                                                                                                                        • 給出一個已經從小到大排序後的數組,要求在數組中找到插入 target 元素的位置。
                                                                                                                        • +
                                                                                                                        • 這一題是經典的二分搜索的變種題,在有序數組中找到最後一個比 target 小的元素。 +- 只要看到面試題裡給出的數組是有序數組,都可以想一想是否可以使用二分法
                                                                                                                        • +
                                                                                                                        +

                                                                                                                        來源

                                                                                                                        + +

                                                                                                                        解答

                                                                                                                        +

                                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0035.Search-Insert-Position/Search-Insert-Position.go

                                                                                                                        +
                                                                                                                        package searchinsertposition
                                                                                                                        +
                                                                                                                        +// 暴力解 時間複雜  O(n) 空間複雜 O(1)
                                                                                                                        +func SearchInsertBurst(nums []int, target int) int {
                                                                                                                        +    for i := 0; i < len(nums); i++ {
                                                                                                                        +        if nums[i] >= target {
                                                                                                                        +            return i
                                                                                                                        +        }
                                                                                                                        +    }
                                                                                                                        +    return len(nums)
                                                                                                                        +}
                                                                                                                        +
                                                                                                                        +//二分法 時間複雜 O(log n) 空間複雜 O(1)
                                                                                                                        +func SearchInsertBisection(nums []int, target int) int {
                                                                                                                        +    left, right := 0, len(nums)-1
                                                                                                                        +    for left <= 2="" right="" {="" ้˜ฒๆญขๆบขๅ‡บ="" ๅŒ(left="" +="" right)="" mid="" :="left" (right-left)="">>1
                                                                                                                        +        if nums[mid] >= target {
                                                                                                                        +            right = mid - 1
                                                                                                                        +        } else if nums[mid] < target {
                                                                                                                        +            left = mid + 1
                                                                                                                        +        } else {
                                                                                                                        +            return mid
                                                                                                                        +        }
                                                                                                                        +    }
                                                                                                                        +    // 分別處理如下四種情況
                                                                                                                        +    // targe在所有元素之前 [0, -1]
                                                                                                                        +    // targe等於數組中某一個元素 return middle;
                                                                                                                        +    // targe在數組中的位置 [left, right],return right + 1
                                                                                                                        +    // targe在數組所有元素之後的情況 [left, right], return right + 1
                                                                                                                        +    return right + 1
                                                                                                                        +}
                                                                                                                        +
                                                                                                                        +//二分法 時間複雜 O(log n) 空間複雜 O(1)
                                                                                                                        +func SearchInsertBisection2(nums []int, target int) int {
                                                                                                                        +    left, right := 0, len(nums)-1
                                                                                                                        +    for left <= 2="" right="" {="" ้˜ฒๆญขๆบขๅ‡บ="" ๅŒ(left="" +="" right)="" mid="" :="left" (right-left)="">>1
                                                                                                                        +        if nums[mid] >= target {
                                                                                                                        +            right = mid - 1
                                                                                                                        +        } else {
                                                                                                                        +            left = mid + 1
                                                                                                                        +        }
                                                                                                                        +    }
                                                                                                                        +    return left
                                                                                                                        +}
                                                                                                                        +
                                                                                                                        +
                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                        + +
                                                                                                                        + +
                                                                                                                        +
                                                                                                                        +
                                                                                                                        + +

                                                                                                                        results matching ""

                                                                                                                        +
                                                                                                                          + +
                                                                                                                          +
                                                                                                                          + +

                                                                                                                          No results matching ""

                                                                                                                          + +
                                                                                                                          +
                                                                                                                          +
                                                                                                                          + +
                                                                                                                          +
                                                                                                                          + +
                                                                                                                          + + + + + + + + + + +
                                                                                                                          + + +
                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0046.Permutations/Permutations.go b/Leetcode/0046.Permutations/Permutations.go new file mode 100644 index 000000000..68cca64e2 --- /dev/null +++ b/Leetcode/0046.Permutations/Permutations.go @@ -0,0 +1,39 @@ +package permutations + +func Permute(nums []int) [][]int { + numsLen := len(nums) + if numsLen == 0 { + return [][]int{} + } + used, path, res := make([]bool, numsLen), []int{}, [][]int{} + dfs(nums, numsLen, 0, path, &used, &res) + return res +} + +/* +generatePermutation: (่ผธๅ…ฅๆ•ธ็ต„, ๆ•ธ็ต„้•ทๅบฆ, ้ž่ฟดๅˆฐ็ฌฌๅนพๅฑคdepth, path, ไฝฟ็”จ้Ž็š„, ็ตๆžœ) +ๆ‰พๆœ€็Ÿญ่ทฏๅพ‘็”จ**BFS**, ๅ…ถไป–ๆ™‚็”จ**DFS**็”จๅพ—ๅคšไธ€ไบ›, ๅ› ็‚บ้ž่ฟด่ผƒๅฅฝๅฏซ +ๅ‡่จญๆœ‰ๆฃตๆปฟ็š„ไบŒๅ‰ๆจน,็ฏ€้ปžๆ•ธ็‚บ N. ๅฐDFSไพ†่ชช็ฉบ้–“่ค‡้›œๅบฆๅฐฑๆ˜ฏ้ž่ฟด, ๆœ€ๅฃž็š„ๆƒ…ๆณๅฐฑๆ˜ฏๆจน็š„้ซ˜ๅบฆ O(log N) +BFS็ฎ—ๆณ•, Queueๆฏๆฌก้ƒฝๆœƒๅญ˜ไบŒๅ‰ๆจนไธ€ๅฑค็š„็ฏ€้ปž, ๆœ€ๅฃž็š„ๆƒ…ๆณไธ‹็ฉบ้–“่ค‡้›œๅบฆๆ‡‰่ฉฒๅฐฑๆ˜ฏๆจน็š„ๆœ€ไธ‹ๅฑค็š„ๆ•ธ้‡, ไนŸๅฐฑๆ˜ฏ N/2. ็ฉบ้–“่ค‡้›œๅบฆ O(N) +DFS๏ผˆๆทฑๅบฆๅ„ชๅ…ˆๆœ็ดข๏ผ‰้€šๅธธไฝฟ็”จๅ †ๆฃง๏ผˆStack๏ผ‰ไพ†ๅฏฆ็พใ€‚ๅœจDFSไธญ๏ผŒๆ‚จ้ฆ–ๅ…ˆ่™•็†ไธ€ๅ€‹็ฏ€้ปž๏ผŒ็„ถๅพŒๅฐ‡ๅ…ถๅญ็ฏ€้ปžๆŒ‰ๆŸ็จฎ้ †ๅบๆŽจๅ…ฅๅ †ๆฃงไธญ๏ผŒๆŽฅ่‘—็นผ็บŒ่™•็†ๅ †ๆฃง้ ‚้ƒจ็š„็ฏ€้ปž๏ผŒ็›ดๅˆฐๅ †ๆฃง็‚บ็ฉบใ€‚ +*/ +func generatePermutation(nums []int, numsLen int, depth int, path []int, used *[]bool, res *[][]int) { + if depth == numsLen { + temp := make([]int, len(path)) + copy(temp, path) + *res = append(*res, temp) + return + } + + for i := 0; i < numsLen; i++ { + if !(*used)[i] { + // ๆฒ’ไฝฟ็”จ้Ž, ๅฐ‡ๅ…ถ็ด€้Œ„่ตฐ้Ž + (*used)[i] = true + path = append(path, nums[i]) + generatePermutation(nums, numsLen, depth+1, path, used, res) + path = path[:len(path)-1] + // ๅ›žๆœ” + (*used)[i] = false + } + } +} diff --git a/Leetcode/0046.Permutations/Permutations_test.go b/Leetcode/0046.Permutations/Permutations_test.go new file mode 100644 index 000000000..370bf3356 --- /dev/null +++ b/Leetcode/0046.Permutations/Permutations_test.go @@ -0,0 +1,31 @@ +package permutations + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + want [][]int +}{ + { + arg1: []int{1, 2, 3}, + want: [][]int{ + {1, 2, 3}, + {1, 3, 2}, + {2, 1, 3}, + {2, 3, 1}, + {3, 1, 2}, + {3, 2, 1}, + }, + }, +} + +func TestPermutations(t *testing.T) { + for _, tt := range tests { + if got := Permute(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Leetcode/0046.Permutations/index.html b/Leetcode/0046.Permutations/index.html new file mode 100644 index 000000000..c5caf7bc9 --- /dev/null +++ b/Leetcode/0046.Permutations/index.html @@ -0,0 +1,3896 @@ + + + + + + + 0046.Permutations ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                          +
                                                                                                                          + + + + + + + + +
                                                                                                                          + +
                                                                                                                          + +
                                                                                                                          + + + + + + + + +
                                                                                                                          +
                                                                                                                          + +
                                                                                                                          +
                                                                                                                          + +
                                                                                                                          + +

                                                                                                                          46. Permutations

                                                                                                                          題目

                                                                                                                          +

                                                                                                                          Given a collection of distinct integers, return all possible permutations(排列). +Example: + Input: [1,2,3] + Output: + [ + [1,2,3], + [1,3,2], + [2,1,3], + [2,3,1], + [3,1,2], + [3,2,1] + ]

                                                                                                                          +

                                                                                                                          題目大意

                                                                                                                          +

                                                                                                                          給定一個沒有重複數字的序列,返回其所有可能的全排列。

                                                                                                                          +

                                                                                                                          解題思路

                                                                                                                          +

                                                                                                                          解決回朔問題可用一個決策樹的遍歷過程

                                                                                                                          +
                                                                                                                            +
                                                                                                                          1. 路徑: 也就是已經做的選擇
                                                                                                                          2. +
                                                                                                                          3. 選擇列表: 也就是當前可以做的選擇
                                                                                                                          4. +
                                                                                                                          5. 結束條件: 也就是達到決策樹底層, 無法再做選擇的條件
                                                                                                                          6. +
                                                                                                                          +
                                                                                                                          result = []
                                                                                                                          +def backtrack(路徑, 選擇列表):
                                                                                                                          +    if 滿足結束條件:
                                                                                                                          +        result.add(路徑)
                                                                                                                          +        return
                                                                                                                          +
                                                                                                                          +    for 選擇 in 選擇列表:
                                                                                                                          +        做選擇
                                                                                                                          +        backtrack(路徑, 選擇列表)
                                                                                                                          +        撤銷選擇
                                                                                                                          +
                                                                                                                          +
                                                                                                                                                 選擇:[1,2,3]
                                                                                                                          +                            []
                                                                                                                          +          [1]/              |[2]            \[3]
                                                                                                                          +        [2]/  \[3]      [1]/  \[3]       [1]/  \[2]
                                                                                                                          +        |[3]   |[2]     |[3]   |[1]      |[2]    |[1]   
                                                                                                                          +結果  [1,2,3]  [1,3,2] [2,1,3] [2,3,1]  [3,1,2]  [3,2,1]
                                                                                                                          +
                                                                                                                          +

                                                                                                                          +
                                                                                                                            +
                                                                                                                          • 求出一個數組的排列組合中的所有排列,用 DFS 深搜即可。 +這個問題可以看作有 ñ 個排列成一行的空格,我們需要從左往右依此填入題目給定的 ñ個數,每個數只能使用一次。 +那麼很直接的可以想到一種窮舉的算法,即從左往右每一個位置都依此嘗試填入一個數, +看能不能填完這ñ 個空格,在程序中我們可以用「回溯法」來模擬這個過程 +回溯法: +一種通過探索所有可能的候選解來找出所有的解的算法。如果候選解被確認不是一個解(或者至少不是最後一個解), +回溯算法會通過在上一步進行一些變化拋棄該解,即回溯並且再次嘗試。
                                                                                                                          • +
                                                                                                                          +

                                                                                                                          作者:LeetCode-Solution +链接:https://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/ +来源:力扣(LeetCode) +著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

                                                                                                                          +

                                                                                                                          來源

                                                                                                                          + +

                                                                                                                          解答

                                                                                                                          +

                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0046.Permutations/Permutations.go

                                                                                                                          +

                                                                                                                          時間複雜 O(n)

                                                                                                                          +
                                                                                                                          package permutations
                                                                                                                          +
                                                                                                                          +func Permute(nums []int) [][]int {
                                                                                                                          +    numsLen := len(nums)
                                                                                                                          +    if numsLen == 0 {
                                                                                                                          +        return [][]int{}
                                                                                                                          +    }
                                                                                                                          +    used, path, res := make([]bool, numsLen), []int{}, [][]int{}
                                                                                                                          +    dfs(nums, numsLen, 0, path, &used, &res)
                                                                                                                          +    return res
                                                                                                                          +}
                                                                                                                          +
                                                                                                                          +/*
                                                                                                                          +generatePermutation: (輸入數組, 數組長度, 遞迴到第幾層depth, path, 使用過的, 結果)
                                                                                                                          +找最短路徑用**BFS**, 其他時用**DFS**用得多一些, 因為遞迴較好寫
                                                                                                                          +假設有棵滿的二叉樹,節點數為 N. 對DFS來說空間複雜度就是遞迴, 最壞的情況就是樹的高度 O(log N)
                                                                                                                          +BFS算法, Queue每次都會存二叉樹一層的節點, 最壞的情況下空間複雜度應該就是樹的最下層的數量, 也就是 N/2. 空間複雜度 O(N)
                                                                                                                          +DFS(深度優先搜索)通常使用堆棧(Stack)來實現。在DFS中,您首先處理一個節點,然後將其子節點按某種順序推入堆棧中,接著繼續處理堆棧頂部的節點,直到堆棧為空。
                                                                                                                          +*/
                                                                                                                          +func generatePermutation(nums []int, numsLen int, depth int, path []int, used *[]bool, res *[][]int) {
                                                                                                                          +    if depth == numsLen {
                                                                                                                          +        temp := make([]int, len(path))
                                                                                                                          +        copy(temp, path)
                                                                                                                          +        *res = append(*res, temp)
                                                                                                                          +        return
                                                                                                                          +    }
                                                                                                                          +
                                                                                                                          +    for i := 0; i < numsLen; i++ {
                                                                                                                          +        if !(*used)[i] {
                                                                                                                          +            // 沒使用過, 將其紀錄走過
                                                                                                                          +            (*used)[i] = true
                                                                                                                          +            path = append(path, nums[i])
                                                                                                                          +            generatePermutation(nums, numsLen, depth+1, path, used, res)
                                                                                                                          +            path = path[:len(path)-1]
                                                                                                                          +            // 回朔
                                                                                                                          +            (*used)[i] = false
                                                                                                                          +        }
                                                                                                                          +    }
                                                                                                                          +}
                                                                                                                          +
                                                                                                                          +
                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                          + +
                                                                                                                          + +
                                                                                                                          +
                                                                                                                          +
                                                                                                                          + +

                                                                                                                          results matching ""

                                                                                                                          +
                                                                                                                            + +
                                                                                                                            +
                                                                                                                            + +

                                                                                                                            No results matching ""

                                                                                                                            + +
                                                                                                                            +
                                                                                                                            +
                                                                                                                            + +
                                                                                                                            +
                                                                                                                            + +
                                                                                                                            + + + + + + + + + + +
                                                                                                                            + + +
                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0049.Group-Anagrams/index.html b/Leetcode/0049.Group-Anagrams/index.html new file mode 100644 index 000000000..3dc24c421 --- /dev/null +++ b/Leetcode/0049.Group-Anagrams/index.html @@ -0,0 +1,3969 @@ + + + + + + + 0049.Group Anagrams ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                            +
                                                                                                                            + + + + + + + + +
                                                                                                                            + +
                                                                                                                            + +
                                                                                                                            + + + + + + + + +
                                                                                                                            +
                                                                                                                            + +
                                                                                                                            +
                                                                                                                            + +
                                                                                                                            + +

                                                                                                                            0049.Grop Anagrams

                                                                                                                            題目

                                                                                                                            +

                                                                                                                            Given an array of strings strs, group the anagrams together. You can return the answer in any order.

                                                                                                                            +

                                                                                                                            An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

                                                                                                                            +

                                                                                                                            Example 1:

                                                                                                                            +

                                                                                                                            Input: strs = ["eat","tea","tan","ate","nat","bat"] +Output: [["bat"],["nat","tan"],["ate","eat","tea"]]

                                                                                                                            +

                                                                                                                            Example 2:

                                                                                                                            +

                                                                                                                            Input: strs = [""] +Output: [[""]]

                                                                                                                            +

                                                                                                                            Example 3:

                                                                                                                            +

                                                                                                                            Input: strs = ["a"] +Output: [["a"]]

                                                                                                                            +

                                                                                                                            Constraints:

                                                                                                                            +
                                                                                                                              +
                                                                                                                            • 1 <= strs.length <= 104
                                                                                                                            • +
                                                                                                                            • 0 <= strs[i].length <= 100
                                                                                                                            • +
                                                                                                                            • strs[i] consists of lowercase English letters.
                                                                                                                            • +
                                                                                                                            +

                                                                                                                            題目大意

                                                                                                                            +

                                                                                                                            分組出只用同樣字符產生的的單字

                                                                                                                            +

                                                                                                                            解題思路

                                                                                                                            +

                                                                                                                            方法一: 計數 +由於互為字母異位詞的兩個字串包含的字母相同,因此兩個字串中的相同字母出現的次數一定是相同的,故可以將每個字母出現的次數使用字串表示,作為哈希表的鍵。

                                                                                                                            +

                                                                                                                            方法二: 排序 +由於互為字母異位詞的兩個字串包含的字母相同,因此對兩個字串分別進行排序之後得到的字串一定是相同的,故可以將排序之後的字串作為哈希表的鍵。

                                                                                                                            +

                                                                                                                            來源

                                                                                                                            + +

                                                                                                                            解答

                                                                                                                            +

                                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0049.Group-Anagams/main.go

                                                                                                                            +
                                                                                                                            package groupanagrams
                                                                                                                            +
                                                                                                                            +import "sort"
                                                                                                                            +
                                                                                                                            +// 使用計數: 時間複雜 O(nk), 空間複雜 O(nk)
                                                                                                                            +// n 是單詞的個數 , k是單字的最大長度
                                                                                                                            +// O(n)遍歷單詞, 遍歷字符O(nk)
                                                                                                                            +func GroupAnagrams(strs []string) [][]string {
                                                                                                                            +    m := make(map[[26]int][]string, len(strs))
                                                                                                                            +
                                                                                                                            +    for _, str := range strs {
                                                                                                                            +        // 建立每一個string的特徵`count`, 藉由統計每個字母出現的次數
                                                                                                                            +        count := [26]int{}
                                                                                                                            +        for _, b := range str {
                                                                                                                            +            count[b-'a']++
                                                                                                                            +        }
                                                                                                                            +        // 將同樣的次數的string放置在 map中
                                                                                                                            +        m[count] = append(m[count], str)
                                                                                                                            +    }
                                                                                                                            +
                                                                                                                            +    // 把map中的string放入到結果的 `[][]string` array 中
                                                                                                                            +    ans := [][]string{}
                                                                                                                            +    for _, v := range m {
                                                                                                                            +        ans = append(ans, v)
                                                                                                                            +    }
                                                                                                                            +    return ans
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +// 排序: 時間複雜 O(nklog(k)), 空間複雜 O(klog(k))
                                                                                                                            +// n 是單詞的個數 , k是單字的最大長度
                                                                                                                            +// 遍歷單詞 O(n)
                                                                                                                            +// 排序字符 O(klog(k))
                                                                                                                            +func GroupAnagramsBySort(strs []string) [][]string {
                                                                                                                            +    m := make(map[string][]string, len(strs))
                                                                                                                            +
                                                                                                                            +    for _, str := range strs {
                                                                                                                            +        // 建立每一個string的特徵, 藉由統計排序
                                                                                                                            +        s := []byte(str)
                                                                                                                            +        sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
                                                                                                                            +        sortedStr := string(s)
                                                                                                                            +
                                                                                                                            +        // 將同樣的特徵的string放置在 map中
                                                                                                                            +        m[sortedStr] = append(m[sortedStr], str)
                                                                                                                            +    }
                                                                                                                            +
                                                                                                                            +    // 把map中的string放入到結果的 `[][]string` array 中
                                                                                                                            +    ans := [][]string{}
                                                                                                                            +    for _, v := range m {
                                                                                                                            +        ans = append(ans, v)
                                                                                                                            +    }
                                                                                                                            +    return ans
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +

                                                                                                                            Benchmark

                                                                                                                            +
                                                                                                                            go test -benchmem -run=none LeetcodeGolang/Leetcode/0049.Group-Anagrams -bench=.
                                                                                                                            +goos: darwin
                                                                                                                            +goarch: amd64
                                                                                                                            +pkg: LeetcodeGolang/Leetcode/0049.Group-Anagrams
                                                                                                                            +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                            +BenchmarkGroupAnagrams-8                  899431              1615 ns/op             968 B/op         12 allocs/op
                                                                                                                            +BenchmarkGroupAnagramsBySort-8            592148              3566 ns/op             776 B/op         33 allocs/op
                                                                                                                            +PASS
                                                                                                                            +ok      LeetcodeGolang/Leetcode/0049.Group-Anagrams     3.611s
                                                                                                                            +
                                                                                                                            +
                                                                                                                            package groupanagrams
                                                                                                                            +
                                                                                                                            +import (
                                                                                                                            +    "reflect"
                                                                                                                            +    "sort"
                                                                                                                            +    "testing"
                                                                                                                            +)
                                                                                                                            +
                                                                                                                            +var tests = []struct {
                                                                                                                            +    arg1 []string
                                                                                                                            +    want [][]string
                                                                                                                            +}{
                                                                                                                            +    {
                                                                                                                            +        []string{"eat", "tea", "tan", "ate", "nat", "bat"},
                                                                                                                            +        [][]string{
                                                                                                                            +            {"bat"}, {"nat", "tan"}, {"ate", "eat", "tea"}},
                                                                                                                            +    },
                                                                                                                            +    {
                                                                                                                            +        []string{},
                                                                                                                            +        [][]string{},
                                                                                                                            +    }, {
                                                                                                                            +        []string{"a"},
                                                                                                                            +        [][]string{
                                                                                                                            +            {"a"}},
                                                                                                                            +    },
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +// 創建一個輔助函數,將字符串數組排序,以便比較
                                                                                                                            +func sortSubStrings(groups [][]string) {
                                                                                                                            +    for _, group := range groups {
                                                                                                                            +        sort.Strings(group)
                                                                                                                            +    }
                                                                                                                            +    // 排序整個切片
                                                                                                                            +    sort.Slice(groups, func(i, j int) bool {
                                                                                                                            +        return groups[i][0] < groups[j][0]
                                                                                                                            +    })
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +func TestGroupAnagrams(t *testing.T) {
                                                                                                                            +    for _, tt := range tests {
                                                                                                                            +        result := GroupAnagrams(tt.arg1)
                                                                                                                            +        // 對結果進行排序,以便比較
                                                                                                                            +        sortSubStrings(result)
                                                                                                                            +
                                                                                                                            +        // 對期望結果進行排序,以便比較
                                                                                                                            +        sortSubStrings(tt.want)
                                                                                                                            +
                                                                                                                            +        // 使用反射檢查結果和期望是否相同
                                                                                                                            +        if !reflect.DeepEqual(result, tt.want) {
                                                                                                                            +            t.Errorf("got = %v, want = %v", result, tt.want)
                                                                                                                            +        }
                                                                                                                            +    }
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +func TestGroupAnagramsBySort(t *testing.T) {
                                                                                                                            +    for _, tt := range tests {
                                                                                                                            +        result := GroupAnagramsBySort(tt.arg1)
                                                                                                                            +        // 對結果進行排序,以便比較
                                                                                                                            +        sortSubStrings(result)
                                                                                                                            +
                                                                                                                            +        // 對期望結果進行排序,以便比較
                                                                                                                            +        sortSubStrings(tt.want)
                                                                                                                            +
                                                                                                                            +        // 使用反射檢查結果和期望是否相同
                                                                                                                            +        if !reflect.DeepEqual(result, tt.want) {
                                                                                                                            +            t.Errorf("got = %v, want = %v", result, tt.want)
                                                                                                                            +        }
                                                                                                                            +    }
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +func BenchmarkGroupAnagrams(b *testing.B) {
                                                                                                                            +    b.ResetTimer()
                                                                                                                            +    for i := 0; i < b.N; i++ {
                                                                                                                            +        GroupAnagrams(tests[0].arg1)
                                                                                                                            +    }
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +func BenchmarkGroupAnagramsBySort(b *testing.B) {
                                                                                                                            +    b.ResetTimer()
                                                                                                                            +    for i := 0; i < b.N; i++ {
                                                                                                                            +        GroupAnagramsBySort(tests[0].arg1)
                                                                                                                            +    }
                                                                                                                            +}
                                                                                                                            +
                                                                                                                            +
                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                            + +
                                                                                                                            + +
                                                                                                                            +
                                                                                                                            +
                                                                                                                            + +

                                                                                                                            results matching ""

                                                                                                                            +
                                                                                                                              + +
                                                                                                                              +
                                                                                                                              + +

                                                                                                                              No results matching ""

                                                                                                                              + +
                                                                                                                              +
                                                                                                                              +
                                                                                                                              + +
                                                                                                                              +
                                                                                                                              + +
                                                                                                                              + + + + + + +
                                                                                                                              + + +
                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0049.Group-Anagrams/main.go b/Leetcode/0049.Group-Anagrams/main.go new file mode 100644 index 000000000..e602fbe20 --- /dev/null +++ b/Leetcode/0049.Group-Anagrams/main.go @@ -0,0 +1,52 @@ +package groupanagrams + +import "sort" + +// ไฝฟ็”จ่จˆๆ•ธ: ๆ™‚้–“่ค‡้›œ O(nk), ็ฉบ้–“่ค‡้›œ O(nk) +// n ๆ˜ฏๅ–ฎ่ฉž็š„ๅ€‹ๆ•ธ , kๆ˜ฏๅ–ฎๅญ—็š„ๆœ€ๅคง้•ทๅบฆ +// O(n)้ๆญทๅ–ฎ่ฉž, ้ๆญทๅญ—็ฌฆO(nk) +func GroupAnagrams(strs []string) [][]string { + m := make(map[[26]int][]string, len(strs)) + + for _, str := range strs { + // ๅปบ็ซ‹ๆฏไธ€ๅ€‹string็š„็‰นๅพต`count`, ่—‰็”ฑ็ตฑ่จˆๆฏๅ€‹ๅญ—ๆฏๅ‡บ็พ็š„ๆฌกๆ•ธ + count := [26]int{} + for _, b := range str { + count[b-'a']++ + } + // ๅฐ‡ๅŒๆจฃ็š„ๆฌกๆ•ธ็š„stringๆ”พ็ฝฎๅœจ mapไธญ + m[count] = append(m[count], str) + } + + // ๆŠŠmapไธญ็š„stringๆ”พๅ…ฅๅˆฐ็ตๆžœ็š„ `[][]string` array ไธญ + ans := [][]string{} + for _, v := range m { + ans = append(ans, v) + } + return ans +} + +// ๆŽ’ๅบ: ๆ™‚้–“่ค‡้›œ O(nklog(k)), ็ฉบ้–“่ค‡้›œ O(klog(k)) +// n ๆ˜ฏๅ–ฎ่ฉž็š„ๅ€‹ๆ•ธ , kๆ˜ฏๅ–ฎๅญ—็š„ๆœ€ๅคง้•ทๅบฆ +// ้ๆญทๅ–ฎ่ฉž O(n) +// ๆŽ’ๅบๅญ—็ฌฆ O(klog(k)) +func GroupAnagramsBySort(strs []string) [][]string { + m := make(map[string][]string, len(strs)) + + for _, str := range strs { + // ๅปบ็ซ‹ๆฏไธ€ๅ€‹string็š„็‰นๅพต, ่—‰็”ฑ็ตฑ่จˆๆŽ’ๅบ + s := []byte(str) + sort.Slice(s, func(i, j int) bool { return s[i] < s[j] }) + sortedStr := string(s) + + // ๅฐ‡ๅŒๆจฃ็š„็‰นๅพต็š„stringๆ”พ็ฝฎๅœจ mapไธญ + m[sortedStr] = append(m[sortedStr], str) + } + + // ๆŠŠmapไธญ็š„stringๆ”พๅ…ฅๅˆฐ็ตๆžœ็š„ `[][]string` array ไธญ + ans := [][]string{} + for _, v := range m { + ans = append(ans, v) + } + return ans +} diff --git a/Leetcode/0049.Group-Anagrams/main_test.go b/Leetcode/0049.Group-Anagrams/main_test.go new file mode 100644 index 000000000..d226e303f --- /dev/null +++ b/Leetcode/0049.Group-Anagrams/main_test.go @@ -0,0 +1,95 @@ +package groupanagrams + +import ( + "reflect" + "sort" + "testing" +) + +var tests = []struct { + arg1 []string + want [][]string +}{ + { + []string{"eat", "tea", "tan", "ate", "nat", "bat"}, + [][]string{ + {"bat"}, {"nat", "tan"}, {"ate", "eat", "tea"}}, + }, + { + []string{}, + [][]string{}, + }, { + []string{"a"}, + [][]string{ + {"a"}}, + }, +} + +// ๅ‰ตๅปบไธ€ๅ€‹่ผ”ๅŠฉๅ‡ฝๆ•ธ๏ผŒๅฐ‡ๅญ—็ฌฆไธฒๆ•ธ็ต„ๆŽ’ๅบ๏ผŒไปฅไพฟๆฏ”่ผƒ +func sortSubStrings(groups [][]string) { + for _, group := range groups { + sort.Strings(group) + } + // ๆŽ’ๅบๆ•ดๅ€‹ๅˆ‡็‰‡ + sort.Slice(groups, func(i, j int) bool { + return groups[i][0] < groups[j][0] + }) +} + +func TestGroupAnagrams(t *testing.T) { + for _, tt := range tests { + result := GroupAnagrams(tt.arg1) + // ๅฐ็ตๆžœ้€ฒ่กŒๆŽ’ๅบ๏ผŒไปฅไพฟๆฏ”่ผƒ + sortSubStrings(result) + + // ๅฐๆœŸๆœ›็ตๆžœ้€ฒ่กŒๆŽ’ๅบ๏ผŒไปฅไพฟๆฏ”่ผƒ + sortSubStrings(tt.want) + + // ไฝฟ็”จๅๅฐ„ๆชขๆŸฅ็ตๆžœๅ’ŒๆœŸๆœ›ๆ˜ฏๅฆ็›ธๅŒ + if !reflect.DeepEqual(result, tt.want) { + t.Errorf("got = %v, want = %v", result, tt.want) + } + } +} + +func TestGroupAnagramsBySort(t *testing.T) { + for _, tt := range tests { + result := GroupAnagramsBySort(tt.arg1) + // ๅฐ็ตๆžœ้€ฒ่กŒๆŽ’ๅบ๏ผŒไปฅไพฟๆฏ”่ผƒ + sortSubStrings(result) + + // ๅฐๆœŸๆœ›็ตๆžœ้€ฒ่กŒๆŽ’ๅบ๏ผŒไปฅไพฟๆฏ”่ผƒ + sortSubStrings(tt.want) + + // ไฝฟ็”จๅๅฐ„ๆชขๆŸฅ็ตๆžœๅ’ŒๆœŸๆœ›ๆ˜ฏๅฆ็›ธๅŒ + if !reflect.DeepEqual(result, tt.want) { + t.Errorf("got = %v, want = %v", result, tt.want) + } + } +} + +func BenchmarkGroupAnagrams(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + GroupAnagrams(tests[0].arg1) + } +} + +func BenchmarkGroupAnagramsBySort(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + GroupAnagramsBySort(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0049.Group-Anagrams -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0049.Group-Anagrams +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkGroupAnagrams-8 899431 1615 ns/op 968 B/op 12 allocs/op +BenchmarkGroupAnagramsBySort-8 592148 3566 ns/op 776 B/op 33 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0049.Group-Anagrams 3.611s +*/ diff --git a/Leetcode/0053.Maximum-Subarray/Maximum-Subarray.go b/Leetcode/0053.Maximum-Subarray/Maximum-Subarray.go new file mode 100644 index 000000000..737df2757 --- /dev/null +++ b/Leetcode/0053.Maximum-Subarray/Maximum-Subarray.go @@ -0,0 +1,56 @@ +package maximumsubarray + +// MaxSubArrayDP : DP (dynamic programming) +func MaxSubArrayDP(nums []int) int { + if len(nums) == 0 { + return 0 + } + + if len(nums) == 1 { + return nums[0] + } + + dp, res := make([]int, len(nums)), nums[0] + dp[0] = nums[0] + + for i := 1; i < len(nums); i++ { + if dp[i-1] > 0 { + // ๅ‰ไธ€ๅ€‹ๅ’Œๆ˜ฏๆญฃ็š„ ็นผ็บŒๅŠ ไธ‹ๅŽป + dp[i] = nums[i] + dp[i-1] + } else { + // ๅ‰ไธ€ๅ€‹ๅ’Œๆ˜ฏๅฐๆ–ผ็ญ‰ๆ–ผ0 ็›ดๆŽฅๆ‹ฟ็พๅœจๅ€ผๅ–ไปฃ + dp[i] = nums[i] + } + res = max(res, dp[i]) + } + return res +} + +// MaxSubArray1 : ๆจกๆ“ฌ, ๆฏ”DPๅฟซ +func MaxSubArray1(nums []int) int { + if len(nums) == 1 { + return nums[0] + } + + maxSum := 0 + tmp := 0 + for i := 0; i < len(nums); i++ { + tmp += nums[i] + if tmp > maxSum { + maxSum = tmp + } + if tmp < 0 { + tmp = 0 + } + } + return maxSum +} + +func max(a int, b int) int { + if a > b { + return a + } + return b +} + +//TODO: ๅˆ†ๆฒปๆณ•, ้€™ๅ€‹ๅˆ†ๆฒปๆ–นๆณ•้กžไผผๆ–ผใ€Œ็ทšๆฎตๆจนๆฑ‚่งฃๆœ€้•ทๅ…ฌๅ…ฑไธŠๅ‡ๅญๅบๅˆ—ๅ•้กŒใ€็š„pushUpๆ“ไฝœ diff --git a/Leetcode/0053.Maximum-Subarray/Maximum-Subarray_test.go b/Leetcode/0053.Maximum-Subarray/Maximum-Subarray_test.go new file mode 100644 index 000000000..0f0c5cf31 --- /dev/null +++ b/Leetcode/0053.Maximum-Subarray/Maximum-Subarray_test.go @@ -0,0 +1,51 @@ +package maximumsubarray + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + arg1: []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}, + want: 6, + }, +} + +func TestMaxSubArrayDP(t *testing.T) { + for _, tt := range tests { + if got := MaxSubArrayDP(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMaxSubArray1(t *testing.T) { + + for _, tt := range tests { + if got := MaxSubArray1(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +var benchArg1 = []int{-2, 1, -3, 4, -1, 2, 1, -5, 4} + +func BenchmarkMaxSubArrayDP(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxSubArrayDP(benchArg1) + } +} +func BenchmarkMaxSubArray1(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxSubArray1(benchArg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0053.Maximum-Subarray -bench=. +BenchmarkMaxSubArrayDP-8 22077684 48.19 ns/op 80 B/op 1 allocs/op +BenchmarkMaxSubArray1-8 94770036 10.74 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Leetcode/0053.Maximum-Subarray/index.html b/Leetcode/0053.Maximum-Subarray/index.html new file mode 100644 index 000000000..088ee3d0f --- /dev/null +++ b/Leetcode/0053.Maximum-Subarray/index.html @@ -0,0 +1,3867 @@ + + + + + + + 0053.Maximum Subarray ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                              +
                                                                                                                              + + + + + + + + +
                                                                                                                              + +
                                                                                                                              + +
                                                                                                                              + + + + + + + + +
                                                                                                                              +
                                                                                                                              + +
                                                                                                                              +
                                                                                                                              + +
                                                                                                                              + +

                                                                                                                              53. Maximum Subarray

                                                                                                                              題目

                                                                                                                              +

                                                                                                                              Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

                                                                                                                              +

                                                                                                                              Example: + Input: [-2,1,-3,4,-1,2,1,-5,4], + Output: 6 + Explanation: [4,-1,2,1] has the largest sum = 6.

                                                                                                                              +

                                                                                                                              Follow up: +If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

                                                                                                                              +

                                                                                                                              題目大意

                                                                                                                              +

                                                                                                                              給定一個整數數組 nums ,找到一個具有最大和的連續子數組(子數組最少包含一個元素),返回其最大和。

                                                                                                                              +

                                                                                                                              解題思路

                                                                                                                              +
                                                                                                                                +
                                                                                                                              • 這一題可以用 DP 求解也可以不用 DP。
                                                                                                                              • +
                                                                                                                              • 題目要求輸出數組中某個區間內數字之和最大的那個值。 dp[i] 表示[0,i] 區間內各個子區間和的最大值,狀態轉移方程是dp[i] = nums[i] + dp[i-1] (dp[i- 1] > 0)dp[i] = nums[i] (dp[i-1] ≤ 0)
                                                                                                                              • +
                                                                                                                              +

                                                                                                                              來源

                                                                                                                              + +

                                                                                                                              解答

                                                                                                                              +

                                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0053.Maximum-Subarray/Maximum-Subarray.go

                                                                                                                              +
                                                                                                                              package maximumsubarray
                                                                                                                              +
                                                                                                                              +// MaxSubArrayDP : DP (dynamic programming)
                                                                                                                              +func MaxSubArrayDP(nums []int) int {
                                                                                                                              +    if len(nums) == 0 {
                                                                                                                              +        return 0
                                                                                                                              +    }
                                                                                                                              +
                                                                                                                              +    if len(nums) == 1 {
                                                                                                                              +        return nums[0]
                                                                                                                              +    }
                                                                                                                              +
                                                                                                                              +    dp, res := make([]int, len(nums)), nums[0]
                                                                                                                              +    dp[0] = nums[0]
                                                                                                                              +
                                                                                                                              +    for i := 1; i < len(nums); i++ {
                                                                                                                              +        if dp[i-1] > 0 {
                                                                                                                              +            // 前一個和是正的 繼續加下去
                                                                                                                              +            dp[i] = nums[i] + dp[i-1]
                                                                                                                              +        } else {
                                                                                                                              +            // 前一個和是小於等於0 直接拿現在值取代
                                                                                                                              +            dp[i] = nums[i]
                                                                                                                              +        }
                                                                                                                              +        res = max(res, dp[i])
                                                                                                                              +    }
                                                                                                                              +    return res
                                                                                                                              +}
                                                                                                                              +
                                                                                                                              +// MaxSubArray1 : 模擬, 比DP快
                                                                                                                              +func MaxSubArray1(nums []int) int {
                                                                                                                              +    if len(nums) == 1 {
                                                                                                                              +        return nums[0]
                                                                                                                              +    }
                                                                                                                              +
                                                                                                                              +    maxSum := 0
                                                                                                                              +    tmp := 0
                                                                                                                              +    for i := 0; i < len(nums); i++ {
                                                                                                                              +        tmp += nums[i]
                                                                                                                              +        if tmp > maxSum {
                                                                                                                              +            maxSum = tmp
                                                                                                                              +        }
                                                                                                                              +        if tmp < 0 {
                                                                                                                              +            tmp = 0
                                                                                                                              +        }
                                                                                                                              +    }
                                                                                                                              +    return maxSum
                                                                                                                              +}
                                                                                                                              +
                                                                                                                              +func max(a int, b int) int {
                                                                                                                              +    if a > b {
                                                                                                                              +        return a
                                                                                                                              +    }
                                                                                                                              +    return b
                                                                                                                              +}
                                                                                                                              +
                                                                                                                              +//TODO: 分治法, 這個分治方法類似於「線段樹求解最長公共上升子序列問題」的pushUp操作
                                                                                                                              +
                                                                                                                              +
                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                              + +
                                                                                                                              + +
                                                                                                                              +
                                                                                                                              +
                                                                                                                              + +

                                                                                                                              results matching ""

                                                                                                                              +
                                                                                                                                + +
                                                                                                                                +
                                                                                                                                + +

                                                                                                                                No results matching ""

                                                                                                                                + +
                                                                                                                                +
                                                                                                                                +
                                                                                                                                + +
                                                                                                                                +
                                                                                                                                + +
                                                                                                                                + + + + + + +
                                                                                                                                + + +
                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II.go b/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II.go new file mode 100644 index 000000000..e52ea8f76 --- /dev/null +++ b/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II.go @@ -0,0 +1,75 @@ +package spiralmatrixii + +// GenerateMatrix : ๆŒ‰ๅฑคๆจกๆ“ฌ, ๆ™‚้–“่ค‡้›œ O(n^2) ็ฉบ้–“่ค‡้›œ O(1) +func GenerateMatrix(n int) [][]int { + result := make([][]int, n) + for i := range result { + result[i] = make([]int, n) + } + + left, right, top, botton := 0, n-1, 0, n-1 + num := 1 + target := n * n + + for num <= target { + // ไธŠๅฑค left to right, ไธŠๅฑค้‚Š็•Œ++ + for i := left; i <= right; i++ { + result[top][i] = num + num++ + } + top++ + + // ๅณๅฑค top to botton , ๅณๅฑค้‚Š็•Œ-- + for i := top; i <= botton; i++ { + result[i][right] = num + num++ + } + right-- + + // ไธ‹ๅฑค right to left , ไธ‹ๅฑค้‚Š็•Œ-- + for i := right; i >= left; i-- { + result[botton][i] = num + num++ + } + botton-- + + // ๅทฆๅฑค botton to top, ๅทฆๅฑค้‚Š็•Œ++ + for i := botton; i >= top; i-- { + result[i][left] = num + num++ + } + left++ + } + + return result +} + +// ๆจกๆ“ฌ : O(n) +// https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0059.Spiral-Matrix-II/ +func GenerateMatrix2(n int) [][]int { + if n == 0 { + return [][]int{} + } + if n == 1 { + return [][]int{{1}} + } + result, visit, round, x, y, spDir := make([][]int, n), make([][]int, n), 0, 0, 0, [][]int{ + {0, 1}, // ๆœๅณ + {1, 0}, // ๆœไธ‹ + {0, -1}, // ๆœๅทฆ + {-1, 0}, // ๆœไธŠ + } + for i := 0; i < n; i++ { + visit[i] = make([]int, n) + result[i] = make([]int, n) + } + visit[x][y] = 1 + result[x][y] = 1 + + for i := 0; i < n*n; i++ { + x += spDir[round%4][0] + y += spDir[round%4][1] + } + + return result +} diff --git a/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II_test.go b/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II_test.go new file mode 100644 index 000000000..ffad304e9 --- /dev/null +++ b/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II_test.go @@ -0,0 +1,32 @@ +package spiralmatrixii + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 int + want [][]int +}{ + { + 2, + [][]int{{1, 2}, {4, 3}}, + }, + { + 3, + [][]int{{1, 2, 3}, {8, 9, 4}, {7, 6, 5}}, + }, + { + 4, + [][]int{{1, 2, 3, 4}, {12, 13, 14, 5}, {11, 16, 15, 6}, {10, 9, 8, 7}}, + }, +} + +func TestGenerateMatrix(t *testing.T) { + for _, tt := range tests { + if got := GenerateMatrix(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Leetcode/0059.Spiral-Matrix-II/index.html b/Leetcode/0059.Spiral-Matrix-II/index.html new file mode 100644 index 000000000..1455f6bbc --- /dev/null +++ b/Leetcode/0059.Spiral-Matrix-II/index.html @@ -0,0 +1,3873 @@ + + + + + + + 0059.Spiral Matrix II ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                +
                                                                                                                                + + + + + + + + +
                                                                                                                                + +
                                                                                                                                + +
                                                                                                                                + + + + + + + + +
                                                                                                                                +
                                                                                                                                + +
                                                                                                                                +
                                                                                                                                + +
                                                                                                                                + +

                                                                                                                                59. Spiral Matrix II

                                                                                                                                題目

                                                                                                                                +

                                                                                                                                Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

                                                                                                                                +

                                                                                                                                Example:

                                                                                                                                +
                                                                                                                                Input: 3
                                                                                                                                +Output:
                                                                                                                                +[
                                                                                                                                + [ 1, 2, 3 ],
                                                                                                                                + [ 8, 9, 4 ],
                                                                                                                                + [ 7, 6, 5 ]
                                                                                                                                +]
                                                                                                                                +

                                                                                                                                題目大意

                                                                                                                                +

                                                                                                                                給定一個正整數 n,生成一個包含 1 到 n^2 所有元素,且元素按順時針順序螺旋排列的正方形矩陣。

                                                                                                                                +

                                                                                                                                解題思路

                                                                                                                                +
                                                                                                                                  +
                                                                                                                                • 給出一個數組 n,要求輸出一個 n n 的二維數組,裡面元素是 1 - nn,且數組排列順序是螺旋排列的
                                                                                                                                • +
                                                                                                                                • 這一題是第 54 題的加強版,沒有需要注意的特殊情況,直接模擬即可。
                                                                                                                                • +
                                                                                                                                +

                                                                                                                                來源

                                                                                                                                + +

                                                                                                                                解答

                                                                                                                                +

                                                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II.go

                                                                                                                                +
                                                                                                                                package spiralmatrixii
                                                                                                                                +
                                                                                                                                +// GenerateMatrix : 按層模擬, 時間複雜 O(n^2) 空間複雜 O(1)
                                                                                                                                +func GenerateMatrix(n int) [][]int {
                                                                                                                                +    result := make([][]int, n)
                                                                                                                                +    for i := range result {
                                                                                                                                +        result[i] = make([]int, n)
                                                                                                                                +    }
                                                                                                                                +
                                                                                                                                +    left, right, top, botton := 0, n-1, 0, n-1
                                                                                                                                +    num := 1
                                                                                                                                +    target := n * n
                                                                                                                                +
                                                                                                                                +    for num <= target="" {="" ไธŠๅฑค="" left="" to="" right,="" ไธŠๅฑค้‚Š็•Œ++="" for="" i="" :="left;" <="right;" i++="" result[top][i]="num" num++="" }="" top++="" ๅณๅฑค="" top="" botton="" ,="" ๅณๅฑค้‚Š็•Œ--="" result[i][right]="num" right--="" ไธ‹ๅฑค="" right="" ไธ‹ๅฑค้‚Š็•Œ--="">= left; i-- {
                                                                                                                                +            result[botton][i] = num
                                                                                                                                +            num++
                                                                                                                                +        }
                                                                                                                                +        botton--
                                                                                                                                +
                                                                                                                                +        // 左層  botton to top, 左層邊界++
                                                                                                                                +        for i := botton; i >= top; i-- {
                                                                                                                                +            result[i][left] = num
                                                                                                                                +            num++
                                                                                                                                +        }
                                                                                                                                +        left++
                                                                                                                                +    }
                                                                                                                                +
                                                                                                                                +    return result
                                                                                                                                +}
                                                                                                                                +
                                                                                                                                +// 模擬 : O(n)
                                                                                                                                +// https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0059.Spiral-Matrix-II/
                                                                                                                                +func GenerateMatrix2(n int) [][]int {
                                                                                                                                +    if n == 0 {
                                                                                                                                +        return [][]int{}
                                                                                                                                +    }
                                                                                                                                +    if n == 1 {
                                                                                                                                +        return [][]int{{1}}
                                                                                                                                +    }
                                                                                                                                +    result, visit, round, x, y, spDir := make([][]int, n), make([][]int, n), 0, 0, 0, [][]int{
                                                                                                                                +        {0, 1},  // 朝右
                                                                                                                                +        {1, 0},  // 朝下
                                                                                                                                +        {0, -1}, // 朝左
                                                                                                                                +        {-1, 0}, // 朝上
                                                                                                                                +    }
                                                                                                                                +    for i := 0; i < n; i++ {
                                                                                                                                +        visit[i] = make([]int, n)
                                                                                                                                +        result[i] = make([]int, n)
                                                                                                                                +    }
                                                                                                                                +    visit[x][y] = 1
                                                                                                                                +    result[x][y] = 1
                                                                                                                                +
                                                                                                                                +    for i := 0; i < n*n; i++ {
                                                                                                                                +        x += spDir[round%4][0]
                                                                                                                                +        y += spDir[round%4][1]
                                                                                                                                +    }
                                                                                                                                +
                                                                                                                                +    return result
                                                                                                                                +}
                                                                                                                                +
                                                                                                                                +
                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                + +
                                                                                                                                + +
                                                                                                                                +
                                                                                                                                +
                                                                                                                                + +

                                                                                                                                results matching ""

                                                                                                                                +
                                                                                                                                  + +
                                                                                                                                  +
                                                                                                                                  + +

                                                                                                                                  No results matching ""

                                                                                                                                  + +
                                                                                                                                  +
                                                                                                                                  +
                                                                                                                                  + +
                                                                                                                                  +
                                                                                                                                  + +
                                                                                                                                  + + + + + + +
                                                                                                                                  + + +
                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0070.Climbing-Stairs/index.html b/Leetcode/0070.Climbing-Stairs/index.html new file mode 100644 index 000000000..7facde13b --- /dev/null +++ b/Leetcode/0070.Climbing-Stairs/index.html @@ -0,0 +1,3852 @@ + + + + + + + 0070.Climbing Stairs ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                  +
                                                                                                                                  + + + + + + + + +
                                                                                                                                  + +
                                                                                                                                  + +
                                                                                                                                  + + + + + + + + +
                                                                                                                                  +
                                                                                                                                  + +
                                                                                                                                  +
                                                                                                                                  + +
                                                                                                                                  + +

                                                                                                                                  0070.Climbing Stairs

                                                                                                                                  題目

                                                                                                                                  +

                                                                                                                                  You are climbing a staircase. It takes n steps to reach the top.

                                                                                                                                  +

                                                                                                                                  Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

                                                                                                                                  +

                                                                                                                                  Example 1:

                                                                                                                                  +

                                                                                                                                  Input: n = 2 +Output: 2 +Explanation: There are two ways to climb to the top.

                                                                                                                                  +
                                                                                                                                    +
                                                                                                                                  1. 1 step + 1 step
                                                                                                                                  2. +
                                                                                                                                  3. 2 steps +Example 2:
                                                                                                                                  4. +
                                                                                                                                  +

                                                                                                                                  Input: n = 3 +Output: 3 +Explanation: There are three ways to climb to the top.

                                                                                                                                  +
                                                                                                                                    +
                                                                                                                                  1. 1 step + 1 step + 1 step
                                                                                                                                  2. +
                                                                                                                                  3. 1 step + 2 steps
                                                                                                                                  4. +
                                                                                                                                  5. 2 steps + 1 step
                                                                                                                                  6. +
                                                                                                                                  +

                                                                                                                                  Constraints:

                                                                                                                                  +

                                                                                                                                  1 <= n <= 45

                                                                                                                                  +
                                                                                                                                    +
                                                                                                                                  • Accepted: 2.8M
                                                                                                                                  • +
                                                                                                                                  • Submissions: 5.4M
                                                                                                                                  • +
                                                                                                                                  • Acceptance Rate: 52.3%
                                                                                                                                  • +
                                                                                                                                  +

                                                                                                                                  題目大意

                                                                                                                                  +

                                                                                                                                  類似 Fibonacci Number

                                                                                                                                  +

                                                                                                                                  解題思路

                                                                                                                                  +
                                                                                                                                    +
                                                                                                                                  • 簡單的 DP,經典的爬樓梯問題. 一個樓梯可以由 n-1 和 n-2 的樓梯爬上來。
                                                                                                                                  • +
                                                                                                                                  • 這一題求解的值就是斐波那契數列。
                                                                                                                                  • +
                                                                                                                                  +

                                                                                                                                  Big O

                                                                                                                                  +

                                                                                                                                  時間複雜 : 空間複雜 :

                                                                                                                                  +

                                                                                                                                  來源

                                                                                                                                  + +

                                                                                                                                  解答

                                                                                                                                  +

                                                                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0070.Climbing-Stairs/main.go

                                                                                                                                  +
                                                                                                                                  
                                                                                                                                  +package climbingstairs
                                                                                                                                  +
                                                                                                                                  +// 時間複雜 O(n), 空間複雜 O(n)
                                                                                                                                  +func ClimbStairs(n int) int {
                                                                                                                                  +    dp := make([]int, n+1)
                                                                                                                                  +    dp[0], dp[1] = 1, 1
                                                                                                                                  +
                                                                                                                                  +    for i := 2; i 
                                                                                                                                  +

                                                                                                                                  Benchmark

                                                                                                                                  +
                                                                                                                                  goos: darwin
                                                                                                                                  +goarch: amd64
                                                                                                                                  +pkg: LeetcodeGolang/Leetcode/0070.Climbing-Stairs
                                                                                                                                  +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                  +BenchmarkClimbStairs-8                  10386211               112.1 ns/op           320 B/op          1 allocs/op
                                                                                                                                  +BenchmarkClimbStairsCache-8             10184984               118.8 ns/op           320 B/op          1 allocs/op
                                                                                                                                  +BenchmarkClimbStairsRecursive-8                4         281980486 ns/op             320 B/op          1 allocs/op
                                                                                                                                  +PASS
                                                                                                                                  +ok      LeetcodeGolang/Leetcode/0070.Climbing-Stairs    5.591s
                                                                                                                                  +
                                                                                                                                  +
                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                  + +
                                                                                                                                  + +
                                                                                                                                  +
                                                                                                                                  +
                                                                                                                                  + +

                                                                                                                                  results matching ""

                                                                                                                                  +
                                                                                                                                    + +
                                                                                                                                    +
                                                                                                                                    + +

                                                                                                                                    No results matching ""

                                                                                                                                    + +
                                                                                                                                    +
                                                                                                                                    +
                                                                                                                                    + +
                                                                                                                                    +
                                                                                                                                    + +
                                                                                                                                    + + + + + + +
                                                                                                                                    + + +
                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0070.Climbing-Stairs/main.go b/Leetcode/0070.Climbing-Stairs/main.go new file mode 100644 index 000000000..d3b513bca --- /dev/null +++ b/Leetcode/0070.Climbing-Stairs/main.go @@ -0,0 +1,39 @@ +package climbingstairs + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(n) +func ClimbStairs(n int) int { + dp := make([]int, n+1) + dp[0], dp[1] = 1, 1 + + for i := 2; i <= n; i++ { + dp[i] = dp[i-1] + dp[i-2] + } + return dp[n] +} + +func ClimbStairsCache(n int) int { + dp := make([]int, n+1) + dp[0], dp[1] = 1, 1 + + for i := 2; i <= n; i++ { + if val := dp[i]; val == 0 { + dp[i] = dp[i-1] + dp[i-2] + } + } + return dp[n] +} + +func ClimbStairsRecursive(n int) int { + dp := make([]int, n+1) + // dp[0], dp[1] = 1, 1 + + var climbClosure func(n int) int + climbClosure = func(n int) int { + if n <= 2 { + return n + } + dp[n] = climbClosure(n-1) + climbClosure(n-2) + return dp[n] + } + return climbClosure(n) +} diff --git a/Leetcode/0070.Climbing-Stairs/main_test.go b/Leetcode/0070.Climbing-Stairs/main_test.go new file mode 100644 index 000000000..df556bc7e --- /dev/null +++ b/Leetcode/0070.Climbing-Stairs/main_test.go @@ -0,0 +1,82 @@ +package climbingstairs + +import "testing" + +var tests = []struct { + arg1 int + want int +}{ + { + 2, + 2, + }, + { + 3, + 3, + }, + { + 39, + 63245986, + }, +} + +func TestClimbStairs(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := ClimbStairs(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestClimbStairsCache(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := ClimbStairsCache(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestClimbStairsRecursive(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := ClimbStairsRecursive(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkClimbStairs(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ClimbStairs(tests[2].arg1) + } +} + +func BenchmarkClimbStairsCache(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ClimbStairsCache(tests[2].arg1) + } +} + +func BenchmarkClimbStairsRecursive(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ClimbStairsRecursive(tests[2].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0070.Climbing-Stairs -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0070.Climbing-Stairs +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkClimbStairs-8 10386211 112.1 ns/op 320 B/op 1 allocs/op +BenchmarkClimbStairsCache-8 10184984 118.8 ns/op 320 B/op 1 allocs/op +BenchmarkClimbStairsRecursive-8 4 281980486 ns/op 320 B/op 1 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0070.Climbing-Stairs 5.591s +*/ diff --git a/Leetcode/0072.Edit-Distance/index.html b/Leetcode/0072.Edit-Distance/index.html new file mode 100644 index 000000000..20ca0d00a --- /dev/null +++ b/Leetcode/0072.Edit-Distance/index.html @@ -0,0 +1,4021 @@ + + + + + + + 0072. Edit Distance ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                    +
                                                                                                                                    + + + + + + + + +
                                                                                                                                    + +
                                                                                                                                    + +
                                                                                                                                    + + + + + + + + +
                                                                                                                                    +
                                                                                                                                    + +
                                                                                                                                    +
                                                                                                                                    + +
                                                                                                                                    + +

                                                                                                                                    0072. Edit Distance

                                                                                                                                    题目

                                                                                                                                    +

                                                                                                                                    Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

                                                                                                                                    +

                                                                                                                                    You have the following three operations permitted on a word:

                                                                                                                                    +
                                                                                                                                      +
                                                                                                                                    • Insert a character
                                                                                                                                    • +
                                                                                                                                    • Delete a character
                                                                                                                                    • +
                                                                                                                                    • Replace a character
                                                                                                                                    • +
                                                                                                                                    +

                                                                                                                                    Example 1:

                                                                                                                                    +
                                                                                                                                    Input: word1 = "horse", word2 = "ros"
                                                                                                                                    +Output: 3
                                                                                                                                    +Explanation: 
                                                                                                                                    +horse -> rorse (replace 'h' with 'r')
                                                                                                                                    +rorse -> rose (remove 'r')
                                                                                                                                    +rose -> ros (remove 'e')
                                                                                                                                    +

                                                                                                                                    Example 2:

                                                                                                                                    +
                                                                                                                                    Input: word1 = "intention", word2 = "execution"
                                                                                                                                    +Output: 5
                                                                                                                                    +Explanation: 
                                                                                                                                    +intention -> inention (remove 't')
                                                                                                                                    +inention -> enention (replace 'i' with 'e')
                                                                                                                                    +enention -> exention (replace 'n' with 'x')
                                                                                                                                    +exention -> exection (replace 'n' with 'c')
                                                                                                                                    +exection -> execution (insert 'u')
                                                                                                                                    +

                                                                                                                                    Constraints:

                                                                                                                                    +
                                                                                                                                      +
                                                                                                                                    • 0 <= word1.length, word2.length <= 500
                                                                                                                                    • +
                                                                                                                                    • word1 and word2 consist of lowercase English letters.
                                                                                                                                    • +
                                                                                                                                    +

                                                                                                                                    題目大意

                                                                                                                                    +

                                                                                                                                    可以對一個字符串進行三種操作, 插入, 刪除, 替換 +現在給你兩個字符串word1,word2, 計算出word1轉換成word2最少需要多少次操作

                                                                                                                                    +

                                                                                                                                    解題思路

                                                                                                                                    +

                                                                                                                                    https://mp.weixin.qq.com/s/ShoZRjM8OyvDbZwoXh6ygg +解決兩個字符串的動態規劃問題, 一班都是用兩個指針 i, j 分別指向兩個字符串的最後, 然後一步步往前走, 縮小問題的規模

                                                                                                                                    +
                                                                                                                                    if word1[i] == word2[j]:
                                                                                                                                    +    skip
                                                                                                                                    +    i,j同時往前
                                                                                                                                    +else:
                                                                                                                                    +    # insert
                                                                                                                                    +    # delete
                                                                                                                                    +    # replace
                                                                                                                                    +
                                                                                                                                    +
                                                                                                                                    dp = [
                                                                                                                                    +    [0,1,2,3,4,5],
                                                                                                                                    +    [1,1,2,2,3,4],
                                                                                                                                    +    [2,2,1,2,3,4],
                                                                                                                                    +    [3,3,2,2,2,3]
                                                                                                                                    +]
                                                                                                                                    +
                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                    word1 \ word2""horse
                                                                                                                                    ""012345
                                                                                                                                    r112234
                                                                                                                                    o221234
                                                                                                                                    s332223
                                                                                                                                    +

                                                                                                                                    dp(i,j) 返回值, 就是 word1[0..i] 和 word2[0..j]的最小編輯距離 +dp(1,0) "ro" , "h" 最小編輯距離 2

                                                                                                                                    + + + + + + + + + + + + + +
                                                                                                                                    dp[i-1][j-1]dp[i-1][j]
                                                                                                                                    dp[i][j-1]dp[i][j]
                                                                                                                                    + + + + + + + + + + + + +
                                                                                                                                    替換/跳過刪除
                                                                                                                                    插入
                                                                                                                                    +

                                                                                                                                    來源

                                                                                                                                    + +

                                                                                                                                    解答

                                                                                                                                    +

                                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0072.Edit-Distance/main.go

                                                                                                                                    +
                                                                                                                                    package editdistance
                                                                                                                                    +
                                                                                                                                    +import "fmt"
                                                                                                                                    +
                                                                                                                                    +// 遞迴 (暴力解)
                                                                                                                                    +func MinDistance(word1 string, word2 string) int {
                                                                                                                                    +    var dp func(int, int) int
                                                                                                                                    +    dp = func(i, j int) int {
                                                                                                                                    +        // base case
                                                                                                                                    +        if i == -1 {
                                                                                                                                    +            return j + 1
                                                                                                                                    +        }
                                                                                                                                    +        if j == -1 {
                                                                                                                                    +            return i + 1
                                                                                                                                    +        }
                                                                                                                                    +        if word1[i] == word2[j] {
                                                                                                                                    +            // word1[0..i] 和 word2[0..j]的最小編輯距離等於 word1[0..i-1] 和 word2[0..j-1]
                                                                                                                                    +            // 本來就相等所以不需要任何操作
                                                                                                                                    +            // 也就是說 dp(i,j)等於 dp(i-1,j-1)
                                                                                                                                    +            return dp(i-1, j-1)
                                                                                                                                    +        } else {
                                                                                                                                    +            return min(
                                                                                                                                    +                dp(i, j-1)+1,   // insert: 直接在 word1[i]中插入一個和word2[j]一樣的字符, 那麼word2[j]就被匹配了,往前j, 繼續和i對比, 操作次數+1
                                                                                                                                    +                dp(i-1, j)+1,   // delete: 直接把 word1[i] 這個字符串刪除, 往前 i 繼續和 j 對比, 操作次數+1
                                                                                                                                    +                dp(i-1, j-1)+1, // replace: 直接把 word1[i] 替換成 word2[j], 這樣他們就匹配了, 同時往前 i, j 繼續對比, 操作次數+1
                                                                                                                                    +            )
                                                                                                                                    +        }
                                                                                                                                    +    }
                                                                                                                                    +
                                                                                                                                    +    return dp(len(word1)-1, len(word2)-1)
                                                                                                                                    +}
                                                                                                                                    +
                                                                                                                                    +// Memo優化
                                                                                                                                    +func MinDistanceMemo(word1 string, word2 string) int {
                                                                                                                                    +    var dp func(int, int) int
                                                                                                                                    +    memo := map[string]int{}
                                                                                                                                    +    dp = func(i, j int) int {
                                                                                                                                    +        key := fmt.Sprintf("%d,%d", i, j)
                                                                                                                                    +        // 查詢備忘錄 避免重複
                                                                                                                                    +        if _, ok := memo[key]; ok == true {
                                                                                                                                    +            return memo[key]
                                                                                                                                    +        }
                                                                                                                                    +
                                                                                                                                    +        // base case
                                                                                                                                    +        if i == -1 {
                                                                                                                                    +            return j + 1
                                                                                                                                    +        }
                                                                                                                                    +        if j == -1 {
                                                                                                                                    +            return i + 1
                                                                                                                                    +        }
                                                                                                                                    +        if word1[i] == word2[j] {
                                                                                                                                    +            // word1[0..i] 和 word2[0..j]的最小編輯距離等於 word1[0..i-1] 和 word2[0..j-1]
                                                                                                                                    +            // 本來就相等所以不需要任何操作
                                                                                                                                    +            // 也就是說 dp(i,j)等於 dp(i-1,j-1)
                                                                                                                                    +            memo[key] = dp(i-1, j-1)
                                                                                                                                    +        } else {
                                                                                                                                    +            memo[key] = min(
                                                                                                                                    +                dp(i, j-1)+1,   // insert: 直接在 word1[i]中插入一個和word2[j]一樣的字符, 那麼word2[j]就被匹配了,往前j, 繼續和i對比, 操作次數+1
                                                                                                                                    +                dp(i-1, j)+1,   // delete: 直接把 word1[i] 這個字符串刪除, 往前 i 繼續和 j 對比, 操作次數+1
                                                                                                                                    +                dp(i-1, j-1)+1, // replace: 直接把 word1[i] 替換成 word2[j], 這樣他們就匹配了, 同時往前 i, j 繼續對比, 操作次數+1
                                                                                                                                    +            )
                                                                                                                                    +        }
                                                                                                                                    +        return memo[key]
                                                                                                                                    +    }
                                                                                                                                    +
                                                                                                                                    +    return dp(len(word1)-1, len(word2)-1)
                                                                                                                                    +}
                                                                                                                                    +
                                                                                                                                    +// DP table 優化, DP table 是自底向上求解, 遞迴是自頂向下求解
                                                                                                                                    +func MinDistanceDP(word1 string, word2 string) int {
                                                                                                                                    +    m, n := len(word1), len(word2)
                                                                                                                                    +    // 初始化  dp table : [][]int{}
                                                                                                                                    +    dp := make([][]int, m+1)
                                                                                                                                    +    for i := 0; i < m+1; i++ {
                                                                                                                                    +        dp[i] = make([]int, n+1)
                                                                                                                                    +    }
                                                                                                                                    +
                                                                                                                                    +    // base case
                                                                                                                                    +    for i := 1; i <= m;="" i++="" {="" dp[i][0]="i" }="" for="" j="" :="1;" <="n;" j++="" dp[0][j]="j" ๅ‘ไธŠๆฑ‚่งฃ="" i="" if="" word1[i-1]="=" word2[j-1]="" dp[i][j]="dp[i-1][j-1]" else="" dp[i][j-1]+1,="" insert="" dp[i-1][j]+1,="" delete="" dp[i-1][j-1]+1,="" replace="" )="" return="" dp[m][n]="" type="" number="" interface="" int="" |="" int64="" float64="" func="" min[t="" number](vars="" ...t)="" t="" min="" _,="" vars=""> i {
                                                                                                                                    +            min = i
                                                                                                                                    +        }
                                                                                                                                    +    }
                                                                                                                                    +
                                                                                                                                    +    return min
                                                                                                                                    +}
                                                                                                                                    +
                                                                                                                                    +
                                                                                                                                    go test -benchmem -run=none LeetcodeGolang/Leetcode/0072.Edit-Distance -bench=.
                                                                                                                                    +goos: darwin
                                                                                                                                    +goarch: amd64
                                                                                                                                    +pkg: LeetcodeGolang/Leetcode/0072.Edit-Distance
                                                                                                                                    +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                    +BenchmarkMinDistance-8            398260              3748 ns/op               0 B/op          0 allocs/op
                                                                                                                                    +BenchmarkMinDistanceMemo-8        102272             10796 ns/op            2211 B/op         69 allocs/op
                                                                                                                                    +BenchmarkMinDistanceDP-8         1944886               794.2 ns/op           688 B/op          9 allocs/op
                                                                                                                                    +PASS
                                                                                                                                    +ok      LeetcodeGolang/Leetcode/0072.Edit-Distance      5.717s
                                                                                                                                    +
                                                                                                                                    +
                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                    + +
                                                                                                                                    + +
                                                                                                                                    +
                                                                                                                                    +
                                                                                                                                    + +

                                                                                                                                    results matching ""

                                                                                                                                    +
                                                                                                                                      + +
                                                                                                                                      +
                                                                                                                                      + +

                                                                                                                                      No results matching ""

                                                                                                                                      + +
                                                                                                                                      +
                                                                                                                                      +
                                                                                                                                      + +
                                                                                                                                      +
                                                                                                                                      + +
                                                                                                                                      + + + + + + +
                                                                                                                                      + + +
                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0072.Edit-Distance/main.go b/Leetcode/0072.Edit-Distance/main.go new file mode 100644 index 000000000..8588faa4f --- /dev/null +++ b/Leetcode/0072.Edit-Distance/main.go @@ -0,0 +1,117 @@ +package editdistance + +import "fmt" + +// ้ž่ฟด (ๆšดๅŠ›่งฃ) +func MinDistance(word1 string, word2 string) int { + var dp func(int, int) int + dp = func(i, j int) int { + // base case + if i == -1 { + return j + 1 + } + if j == -1 { + return i + 1 + } + if word1[i] == word2[j] { + // word1[0..i] ๅ’Œ word2[0..j]็š„ๆœ€ๅฐ็ทจ่ผฏ่ท้›ข็ญ‰ๆ–ผ word1[0..i-1] ๅ’Œ word2[0..j-1] + // ๆœฌไพ†ๅฐฑ็›ธ็ญ‰ๆ‰€ไปฅไธ้œ€่ฆไปปไฝ•ๆ“ไฝœ + // ไนŸๅฐฑๆ˜ฏ่ชช dp(i,j)็ญ‰ๆ–ผ dp(i-1,j-1) + return dp(i-1, j-1) + } else { + return min( + dp(i, j-1)+1, // insert: ็›ดๆŽฅๅœจ word1[i]ไธญๆ’ๅ…ฅไธ€ๅ€‹ๅ’Œword2[j]ไธ€ๆจฃ็š„ๅญ—็ฌฆ, ้‚ฃ้บผword2[j]ๅฐฑ่ขซๅŒน้…ไบ†,ๅพ€ๅ‰j, ็นผ็บŒๅ’Œiๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 + dp(i-1, j)+1, // delete: ็›ดๆŽฅๆŠŠ word1[i] ้€™ๅ€‹ๅญ—็ฌฆไธฒๅˆช้™ค, ๅพ€ๅ‰ i ็นผ็บŒๅ’Œ j ๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 + dp(i-1, j-1)+1, // replace: ็›ดๆŽฅๆŠŠ word1[i] ๆ›ฟๆ›ๆˆ word2[j], ้€™ๆจฃไป–ๅ€‘ๅฐฑๅŒน้…ไบ†, ๅŒๆ™‚ๅพ€ๅ‰ i, j ็นผ็บŒๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 + ) + } + } + + return dp(len(word1)-1, len(word2)-1) +} + +// Memoๅ„ชๅŒ– +func MinDistanceMemo(word1 string, word2 string) int { + var dp func(int, int) int + memo := map[string]int{} + dp = func(i, j int) int { + key := fmt.Sprintf("%d,%d", i, j) + // ๆŸฅ่ฉขๅ‚™ๅฟ˜้Œ„ ้ฟๅ…้‡่ค‡ + if _, ok := memo[key]; ok == true { + return memo[key] + } + + // base case + if i == -1 { + return j + 1 + } + if j == -1 { + return i + 1 + } + if word1[i] == word2[j] { + // word1[0..i] ๅ’Œ word2[0..j]็š„ๆœ€ๅฐ็ทจ่ผฏ่ท้›ข็ญ‰ๆ–ผ word1[0..i-1] ๅ’Œ word2[0..j-1] + // ๆœฌไพ†ๅฐฑ็›ธ็ญ‰ๆ‰€ไปฅไธ้œ€่ฆไปปไฝ•ๆ“ไฝœ + // ไนŸๅฐฑๆ˜ฏ่ชช dp(i,j)็ญ‰ๆ–ผ dp(i-1,j-1) + memo[key] = dp(i-1, j-1) + } else { + memo[key] = min( + dp(i, j-1)+1, // insert: ็›ดๆŽฅๅœจ word1[i]ไธญๆ’ๅ…ฅไธ€ๅ€‹ๅ’Œword2[j]ไธ€ๆจฃ็š„ๅญ—็ฌฆ, ้‚ฃ้บผword2[j]ๅฐฑ่ขซๅŒน้…ไบ†,ๅพ€ๅ‰j, ็นผ็บŒๅ’Œiๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 + dp(i-1, j)+1, // delete: ็›ดๆŽฅๆŠŠ word1[i] ้€™ๅ€‹ๅญ—็ฌฆไธฒๅˆช้™ค, ๅพ€ๅ‰ i ็นผ็บŒๅ’Œ j ๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 + dp(i-1, j-1)+1, // replace: ็›ดๆŽฅๆŠŠ word1[i] ๆ›ฟๆ›ๆˆ word2[j], ้€™ๆจฃไป–ๅ€‘ๅฐฑๅŒน้…ไบ†, ๅŒๆ™‚ๅพ€ๅ‰ i, j ็นผ็บŒๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 + ) + } + return memo[key] + } + + return dp(len(word1)-1, len(word2)-1) +} + +// DP table ๅ„ชๅŒ–, DP table ๆ˜ฏ่‡ชๅบ•ๅ‘ไธŠๆฑ‚่งฃ, ้ž่ฟดๆ˜ฏ่‡ช้ ‚ๅ‘ไธ‹ๆฑ‚่งฃ +func MinDistanceDP(word1 string, word2 string) int { + m, n := len(word1), len(word2) + // ๅˆๅง‹ๅŒ– dp table : [][]int{} + dp := make([][]int, m+1) + for i := 0; i < m+1; i++ { + dp[i] = make([]int, n+1) + } + + // base case + for i := 1; i <= m; i++ { + dp[i][0] = i + } + for j := 1; j <= n; j++ { + dp[0][j] = j + } + + // ๅ‘ไธŠๆฑ‚่งฃ + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + if word1[i-1] == word2[j-1] { + dp[i][j] = dp[i-1][j-1] + } else { + dp[i][j] = min( + dp[i][j-1]+1, // insert + dp[i-1][j]+1, // delete + dp[i-1][j-1]+1, // replace + ) + } + } + } + return dp[m][n] +} + +type Number interface { + int | int64 | float64 +} + +func min[T Number](vars ...T) T { + min := vars[0] + + for _, i := range vars { + if min > i { + min = i + } + } + + return min +} diff --git a/Leetcode/0072.Edit-Distance/main_test.go b/Leetcode/0072.Edit-Distance/main_test.go new file mode 100644 index 000000000..378c1821c --- /dev/null +++ b/Leetcode/0072.Edit-Distance/main_test.go @@ -0,0 +1,78 @@ +package editdistance + +import "testing" + +var tests = []struct { + arg1 string + arg2 string + want int +}{ + { + "horse", + "ros", + 3, + }, + { + "intention", + "execution", + 5, + }, +} + +func TestMinDistance(t *testing.T) { + for _, tt := range tests { + if got := MinDistance(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMinDistanceMemo(t *testing.T) { + for _, tt := range tests { + if got := MinDistanceMemo(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMinDistanceDP(t *testing.T) { + for _, tt := range tests { + if got := MinDistanceDP(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkMinDistance(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinDistance(tests[i%2].arg1, tests[i%2].arg2) + } +} + +func BenchmarkMinDistanceMemo(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinDistanceMemo(tests[i%2].arg1, tests[i%2].arg2) + } +} + +func BenchmarkMinDistanceDP(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinDistanceDP(tests[i%2].arg1, tests[i%2].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0072.Edit-Distance -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0072.Edit-Distance +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkMinDistance-8 398260 3748 ns/op 0 B/op 0 allocs/op +BenchmarkMinDistanceMemo-8 102272 10796 ns/op 2211 B/op 69 allocs/op +BenchmarkMinDistanceDP-8 1944886 794.2 ns/op 688 B/op 9 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0072.Edit-Distance 5.717s +*/ diff --git a/Leetcode/0075.Sort-Colors/0075.Sort-Colors.go b/Leetcode/0075.Sort-Colors/0075.Sort-Colors.go new file mode 100644 index 000000000..31ca4f4ab --- /dev/null +++ b/Leetcode/0075.Sort-Colors/0075.Sort-Colors.go @@ -0,0 +1,73 @@ +package sortcolors + +func sortColors(nums []int) { + if len(nums) == 0 { + return + } + + var index0, index1, index2 = 0, 0, 0 + for _, num := range nums { + switch num { + case 0: + nums[index2] = 2 + index2++ + nums[index1] = 1 + index1++ + nums[index0] = 0 + index0++ + case 1: + nums[index2] = 2 + index2++ + nums[index1] = 1 + index1++ + case 2: + index2++ + } + } +} + +/* +ไบŒ่ทฏๅฟซๆŽ’่ˆ‡ไธ‰่ทฏๅฟซๆŽ’ +ๅ…ˆๆŽŒๆกไบŒ่ทฏๅฟซๆŽ’๏ผŒ https://leetcode-cn.com/problems/sort-an-array/solution/golang-er-lu-kuai-pai-by-rqb-2/ +ไธ‰่ทฏๅฟซๆŽ’็จๅพฎๆ”นไธ‹ๅณๅฏ + +ๅ€ๅˆฅ๏ผš +ไบŒ่ทฏๅฟซๆŽ’๏ผŒๅˆ†ๅ…ฉ้ƒจๅˆ†๏ผšๅฐๆ–ผ็ญ‰ๆ–ผใ€ๅคงๆ–ผไบŒ้ƒจๅˆ†ใ€‚ +ไธ‰่ทฏๅฟซๆŽ’ๅˆ†็‚บ๏ผŒๅฐๆ–ผใ€็ญ‰ๆ–ผใ€ๅคงๆ–ผไธ‰้ƒจๅˆ†ใ€‚ + +ไธ‰่ทฏๅฟซๆŽ’๏ผš +็›ธๆฏ”ไบŒ่ทฏๅฟซๆŽ’ๅขžๅŠ ไธ€ๅ€‹่ฎŠ้‡่จ˜้Œ„็›ธ็ญ‰็š„่ตทๅง‹ๅ…ƒ็ด ใ€‚ +ๅ‡่จญ้ธๆ“‡ๆ•ธ็ต„็ฌฌไธ€ๅ€‹ๅ…ƒ็ด ไฝœ็‚บๅƒ่€ƒๅ…ƒ็ด ใ€‚ๅ‰‡่ตทๅง‹ไธ‹้‚Š็‚บ0๏ผŒๅณ็‚บequalHead + +ไฝœ่€…๏ผšhibrq +้“พๆŽฅ๏ผšhttps://leetcode-cn.com/problems/sort-an-array/solution/golang-san-lu-kuai-pai-by-rqb-2/ +ๆฅๆบ๏ผšๅŠ›ๆ‰ฃ๏ผˆLeetCode๏ผ‰ +่‘—ไฝœๆƒๅฝ’ไฝœ่€…ๆ‰€ๆœ‰ใ€‚ๅ•†ไธš่ฝฌ่ฝฝ่ฏท่”็ณปไฝœ่€…่Žทๅพ—ๆŽˆๆƒ๏ผŒ้žๅ•†ไธš่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๅ‡บๅค„ใ€‚ +*/ +func sortColorsQuickSort(nums []int) { + if len(nums) < 2 { + return + } + + pivot := nums[0] + + head, tail := 0, len(nums)-1 + i := 1 + equalHead := 0 + for head < tail { + if nums[i] < pivot { + nums[i], nums[equalHead] = nums[equalHead], nums[i] + head++ + i++ + equalHead++ + } else if nums[i] == pivot { + i++ + head++ + } else { + nums[i], nums[tail] = nums[tail], nums[i] + tail-- + } + } + sortColorsQuickSort(nums[:equalHead]) + sortColorsQuickSort(nums[tail+1:]) +} diff --git a/Leetcode/0075.Sort-Colors/0075.Sort-Colors_test.go b/Leetcode/0075.Sort-Colors/0075.Sort-Colors_test.go new file mode 100644 index 000000000..65d0bc307 --- /dev/null +++ b/Leetcode/0075.Sort-Colors/0075.Sort-Colors_test.go @@ -0,0 +1,70 @@ +package sortcolors + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + want []int +}{ + { + []int{2, 0, 2, 1, 1, 0}, + []int{0, 0, 1, 1, 2, 2}, + }, + { + []int{2, 0, 1}, + []int{0, 1, 2}, + }, + { + []int{0}, + []int{0}, + }, + { + []int{1}, + []int{1}, + }, +} + +func TestSortColors(t *testing.T) { + + for _, tt := range tests { + sortColors(tt.arg1) + if !reflect.DeepEqual(tt.arg1, tt.want) { + t.Errorf("got = %v, want = %v", tt.arg1, tt.want) + } + } +} + +func TestSortColorsQuickSort(t *testing.T) { + + for _, tt := range tests { + sortColorsQuickSort(tt.arg1) + if !reflect.DeepEqual(tt.arg1, tt.want) { + t.Errorf("got = %v, want = %v", tt.arg1, tt.want) + } + } +} + +func BenchmarkSortColors(b *testing.B) { + arg1 := []int{2, 7, 11, 15} + b.ResetTimer() + for i := 0; i < b.N; i++ { + sortColors(arg1) + } +} + +func BenchmarkSortColorsQuickSort(b *testing.B) { + arg1 := []int{2, 7, 11, 15} + b.ResetTimer() + for i := 0; i < b.N; i++ { + sortColorsQuickSort(arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0075.Sort-Colors -bench=. +BenchmarkSortColors-8 157253976 8.111 ns/op 0 B/op 0 allocs/op +BenchmarkSortColorsQuickSort-8 63078445 20.91 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Leetcode/0075.Sort-Colors/index.html b/Leetcode/0075.Sort-Colors/index.html new file mode 100644 index 000000000..5f647dd1c --- /dev/null +++ b/Leetcode/0075.Sort-Colors/index.html @@ -0,0 +1,3916 @@ + + + + + + + 0075.Sort Colors ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                      +
                                                                                                                                      + + + + + + + + +
                                                                                                                                      + +
                                                                                                                                      + +
                                                                                                                                      + + + + + + + + +
                                                                                                                                      +
                                                                                                                                      + +
                                                                                                                                      +
                                                                                                                                      + +
                                                                                                                                      + +

                                                                                                                                      75. Sort Colors

                                                                                                                                      题目

                                                                                                                                      +

                                                                                                                                      Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.

                                                                                                                                      +

                                                                                                                                      Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

                                                                                                                                      +

                                                                                                                                      Note: You are not suppose to use the library's sort function for this problem.

                                                                                                                                      +

                                                                                                                                      Example 1:

                                                                                                                                      +
                                                                                                                                      Input: [2,0,2,1,1,0]
                                                                                                                                      +Output: [0,0,1,1,2,2]
                                                                                                                                      +

                                                                                                                                      Follow up:

                                                                                                                                      +
                                                                                                                                        +
                                                                                                                                      • A rather straight forward solution is a two-pass algorithm using counting sort.
                                                                                                                                        First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.
                                                                                                                                      • +
                                                                                                                                      • Could you come up with a one-pass algorithm using only constant space?
                                                                                                                                      • +
                                                                                                                                      +
                                                                                                                                      +

                                                                                                                                      給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。

                                                                                                                                      +

                                                                                                                                      此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。

                                                                                                                                      +

                                                                                                                                      範例 1:

                                                                                                                                      +
                                                                                                                                      輸入:nums = [2,0,2,1,1,0]
                                                                                                                                      +輸出:[0,0,1,1,2,2]
                                                                                                                                      +

                                                                                                                                      範例 2:

                                                                                                                                      +
                                                                                                                                      輸入:nums = [2,0,1]
                                                                                                                                      +輸出:[0,1,2]
                                                                                                                                      +

                                                                                                                                      範例 3:

                                                                                                                                      +
                                                                                                                                      輸入:nums = [0]
                                                                                                                                      +輸出:[0]
                                                                                                                                      +

                                                                                                                                      範例 4:

                                                                                                                                      +
                                                                                                                                      輸入:nums = [1]
                                                                                                                                      +輸出:[1]
                                                                                                                                      +

                                                                                                                                      提示:

                                                                                                                                      +
                                                                                                                                        +
                                                                                                                                      • n == nums.length
                                                                                                                                      • +
                                                                                                                                      • 1 <= n <= 300
                                                                                                                                      • +
                                                                                                                                      • nums[i] 為 0、1 或 2
                                                                                                                                      • +
                                                                                                                                      +

                                                                                                                                      進階:

                                                                                                                                      +
                                                                                                                                        +
                                                                                                                                      • 你可以不使用代碼庫中的排序函數來解決這道題嗎?
                                                                                                                                      • +
                                                                                                                                      • 你能想出一個僅使用常數空間的一趟掃描算法嗎?
                                                                                                                                      • +
                                                                                                                                      +

                                                                                                                                      來源:力扣(LeetCode) +鏈接:https://leetcode-cn.com/problems/sort-colors +著作權歸領扣網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

                                                                                                                                      +

                                                                                                                                      題目大意

                                                                                                                                      +

                                                                                                                                      抽象題意其實就是排序。這題可以用快排一次通過。

                                                                                                                                      +

                                                                                                                                      解題思路

                                                                                                                                      +

                                                                                                                                      題目末尾的 Follow up 提出了一個更高的要求,能否用一次循環解決問題?這題由於數字只會出現 0,1,2 這三個數字,所以用游標移動來控制順序也是可以的。具體做法:0 是排在最前面的,所以只要添加一個 0,就需要放置 1 和 2。1 排在 2 前面,所以添加 1 的時候也需要放置 2 。至於最後的 2,只用移動游標即可。

                                                                                                                                      +

                                                                                                                                      這道題可以用計數排序,適合待排序數字很少的題目。用一個 3 個容量的數組分別計數,記錄 0,1,2 出現的個數。然後再根據個數排列 0,1,2 即可。時間複雜度 O(n),空間複雜度 O(K)。這一題 K = 3。

                                                                                                                                      +

                                                                                                                                      這道題也可以用一次三路快排。數組分為 3 部分,第一個部分都是 0,中間部分都是 1,最後部分都是 2 。

                                                                                                                                      +

                                                                                                                                      來源

                                                                                                                                      + +

                                                                                                                                      解答

                                                                                                                                      +

                                                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0075.Sort-Colors/0075.Sort-Colors.go

                                                                                                                                      +
                                                                                                                                      package sortcolors
                                                                                                                                      +
                                                                                                                                      +func sortColors(nums []int) {
                                                                                                                                      +    if len(nums) == 0 {
                                                                                                                                      +        return
                                                                                                                                      +    }
                                                                                                                                      +
                                                                                                                                      +    var index0, index1, index2 = 0, 0, 0
                                                                                                                                      +    for _, num := range nums {
                                                                                                                                      +        switch num {
                                                                                                                                      +        case 0:
                                                                                                                                      +            nums[index2] = 2
                                                                                                                                      +            index2++
                                                                                                                                      +            nums[index1] = 1
                                                                                                                                      +            index1++
                                                                                                                                      +            nums[index0] = 0
                                                                                                                                      +            index0++
                                                                                                                                      +        case 1:
                                                                                                                                      +            nums[index2] = 2
                                                                                                                                      +            index2++
                                                                                                                                      +            nums[index1] = 1
                                                                                                                                      +            index1++
                                                                                                                                      +        case 2:
                                                                                                                                      +            index2++
                                                                                                                                      +        }
                                                                                                                                      +    }
                                                                                                                                      +}
                                                                                                                                      +
                                                                                                                                      +/*
                                                                                                                                      +二路快排與三路快排
                                                                                                                                      +先掌握二路快排, https://leetcode-cn.com/problems/sort-an-array/solution/golang-er-lu-kuai-pai-by-rqb-2/
                                                                                                                                      +三路快排稍微改下即可
                                                                                                                                      +
                                                                                                                                      +區別:
                                                                                                                                      +二路快排,分兩部分:小於等於、大於二部分。
                                                                                                                                      +三路快排分為,小於、等於、大於三部分。
                                                                                                                                      +
                                                                                                                                      +三路快排:
                                                                                                                                      +相比二路快排增加一個變量記錄相等的起始元素。
                                                                                                                                      +假設選擇數組第一個元素作為參考元素。則起始下邊為0,即為equalHead
                                                                                                                                      +
                                                                                                                                      +作者:hibrq
                                                                                                                                      +链接:https://leetcode-cn.com/problems/sort-an-array/solution/golang-san-lu-kuai-pai-by-rqb-2/
                                                                                                                                      +来源:力扣(LeetCode)
                                                                                                                                      +著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
                                                                                                                                      +*/
                                                                                                                                      +func sortColorsQuickSort(nums []int) {
                                                                                                                                      +    if len(nums) < 2 {
                                                                                                                                      +        return
                                                                                                                                      +    }
                                                                                                                                      +
                                                                                                                                      +    pivot := nums[0]
                                                                                                                                      +
                                                                                                                                      +    head, tail := 0, len(nums)-1
                                                                                                                                      +    i := 1
                                                                                                                                      +    equalHead := 0
                                                                                                                                      +    for head < tail {
                                                                                                                                      +        if nums[i] < pivot {
                                                                                                                                      +            nums[i], nums[equalHead] = nums[equalHead], nums[i]
                                                                                                                                      +            head++
                                                                                                                                      +            i++
                                                                                                                                      +            equalHead++
                                                                                                                                      +        } else if nums[i] == pivot {
                                                                                                                                      +            i++
                                                                                                                                      +            head++
                                                                                                                                      +        } else {
                                                                                                                                      +            nums[i], nums[tail] = nums[tail], nums[i]
                                                                                                                                      +            tail--
                                                                                                                                      +        }
                                                                                                                                      +    }
                                                                                                                                      +    sortColorsQuickSort(nums[:equalHead])
                                                                                                                                      +    sortColorsQuickSort(nums[tail+1:])
                                                                                                                                      +}
                                                                                                                                      +
                                                                                                                                      +
                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                      + +
                                                                                                                                      + +
                                                                                                                                      +
                                                                                                                                      +
                                                                                                                                      + +

                                                                                                                                      results matching ""

                                                                                                                                      +
                                                                                                                                        + +
                                                                                                                                        +
                                                                                                                                        + +

                                                                                                                                        No results matching ""

                                                                                                                                        + +
                                                                                                                                        +
                                                                                                                                        +
                                                                                                                                        + +
                                                                                                                                        +
                                                                                                                                        + +
                                                                                                                                        + + + + + + +
                                                                                                                                        + + +
                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0078.Subsets/index.html b/Leetcode/0078.Subsets/index.html new file mode 100644 index 000000000..acfa80c2b --- /dev/null +++ b/Leetcode/0078.Subsets/index.html @@ -0,0 +1,3838 @@ + + + + + + + 0078. Subsets ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                        +
                                                                                                                                        + + + + + + + + +
                                                                                                                                        + +
                                                                                                                                        + +
                                                                                                                                        + + + + + + + + +
                                                                                                                                        +
                                                                                                                                        + +
                                                                                                                                        +
                                                                                                                                        + +
                                                                                                                                        + +

                                                                                                                                        0078. Subsets

                                                                                                                                        題目

                                                                                                                                        +

                                                                                                                                        Given an integer array nums of unique elements, return all possible +subsets + (the power set).

                                                                                                                                        +

                                                                                                                                        The solution set must not contain duplicate subsets. Return the solution in any order.

                                                                                                                                        +

                                                                                                                                        Example 1:

                                                                                                                                        +

                                                                                                                                        Input: nums = [1,2,3] +Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] +Example 2:

                                                                                                                                        +

                                                                                                                                        Input: nums = [0] +Output: [[],[0]]

                                                                                                                                        +

                                                                                                                                        Constraints:

                                                                                                                                        +

                                                                                                                                        1 <= nums.length <= 10 +-10 <= nums[i] <= 10 +All the numbers of nums are unique.

                                                                                                                                        +

                                                                                                                                        題目大意

                                                                                                                                        +

                                                                                                                                        給定一組不含重複元素的整數陣列 nums,返回該陣列所有可能的子集(冪集)。 說明:解集不能包含重複的子集。

                                                                                                                                        +

                                                                                                                                        解題思路

                                                                                                                                        +

                                                                                                                                        找出一個集合中的所有子集,空集也算是子集。 且陣列中的數位不會出現重複。 用 DFS 暴力枚舉即可。 +這一題和第 90 題,第 491 題類似,可以一起解答和複習

                                                                                                                                        +

                                                                                                                                        Big O

                                                                                                                                        +

                                                                                                                                        時間複雜 : O(n^2) +空間複雜 : O(n)

                                                                                                                                        +

                                                                                                                                        來源

                                                                                                                                        + +

                                                                                                                                        解答

                                                                                                                                        +

                                                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0078.Subsets/main.go

                                                                                                                                        +
                                                                                                                                        package subsets
                                                                                                                                        +
                                                                                                                                        +// 時間複雜 O(n^2)    , 空間複雜 O(n)
                                                                                                                                        +func Subsets(nums []int) [][]int {
                                                                                                                                        +    path, result := []int{}, [][]int{}
                                                                                                                                        +    for i := 0; i 
                                                                                                                                        +

                                                                                                                                        Benchmark

                                                                                                                                        +
                                                                                                                                        go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. -cover
                                                                                                                                        +goos: darwin
                                                                                                                                        +goarch: amd64
                                                                                                                                        +pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes
                                                                                                                                        +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                        +BenchmarkMaxEnvelopes-8          7799131               160.3 ns/op            88 B/op          3 allocs/op
                                                                                                                                        +BenchmarkMaxEnvelopes2-8         5800399               195.6 ns/op            80 B/op          4 allocs/op
                                                                                                                                        +PASS
                                                                                                                                        +coverage: 96.0% of statements
                                                                                                                                        +ok      LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes     3.726s
                                                                                                                                        +
                                                                                                                                        +
                                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                        + +
                                                                                                                                        + +
                                                                                                                                        +
                                                                                                                                        +
                                                                                                                                        + +

                                                                                                                                        results matching ""

                                                                                                                                        +
                                                                                                                                          + +
                                                                                                                                          +
                                                                                                                                          + +

                                                                                                                                          No results matching ""

                                                                                                                                          + +
                                                                                                                                          +
                                                                                                                                          +
                                                                                                                                          + +
                                                                                                                                          +
                                                                                                                                          + +
                                                                                                                                          + + + + + + +
                                                                                                                                          + + +
                                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0078.Subsets/main.go b/Leetcode/0078.Subsets/main.go new file mode 100644 index 000000000..001eeb191 --- /dev/null +++ b/Leetcode/0078.Subsets/main.go @@ -0,0 +1,42 @@ +package subsets + +// ๆ™‚้–“่ค‡้›œ O(n^2) , ็ฉบ้–“่ค‡้›œ O(n) +func Subsets(nums []int) [][]int { + path, result := []int{}, [][]int{} + for i := 0; i <= len(nums); i++ { + genSubsets(nums, i, 0, path, &result) + } + return result +} + +func genSubsets(nums []int, elemSize, start int, path []int, result *[][]int) { + if len(path) == elemSize { + b := make([]int, len(path)) + copy(b, path) + *result = append(*result, b) + return + } + + for k := start; k < len(nums); k++ { + path = append(path, nums[k]) + genSubsets(nums, elemSize, k+1, path, result) + path = path[:len(path)-1] + } +} + +// ๆ™‚้–“่ค‡้›œ O(n^2) , ็ฉบ้–“่ค‡้›œ O(n) +func SubsetsDFS(nums []int) [][]int { + path, result := []int{}, [][]int{} + genSubsetsDFS(nums, path, &result) + return result +} + +func genSubsetsDFS(nums []int, path []int, result *[][]int) { + b := make([]int, len(path)) + copy(b, path) + *result = append(*result, b) + for i := 0; i < len(nums); i++ { + // nๅ€‹ element ๅœจsliceไธญ + genSubsetsDFS(nums[i+1:], append(path, nums[i]), result) + } +} diff --git a/Leetcode/0078.Subsets/main_test.go b/Leetcode/0078.Subsets/main_test.go new file mode 100644 index 000000000..507c8a880 --- /dev/null +++ b/Leetcode/0078.Subsets/main_test.go @@ -0,0 +1,97 @@ +package subsets + +import ( + "reflect" + "sort" + "testing" +) + +var tests = []struct { + arg1 []int + want [][]int +}{ + { + []int{1, 2, 3}, + [][]int{ + {}, {1}, {1, 2}, {1, 2, 3}, {1, 3}, {2}, {2, 3}, {3}, + }, + }, + { + []int{0}, + [][]int{ + {}, {0}, + }, + }, +} + +func TestSubsets(t *testing.T) { + for _, tt := range tests { + got := Subsets(tt.arg1) + sortOutput(&got) + if !reflect.DeepEqual(got, tt.want) { + // // if got := Subsets(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +//go:cover +func TestSubsetsDFS(t *testing.T) { + for _, tt := range tests { + got := SubsetsDFS(tt.arg1) + sortOutput(&got) + + if !reflect.DeepEqual(got, tt.want) { + // // if got := Subsets(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSubsets(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Subsets(tests[0].arg1) + } +} + +func BenchmarkSubsetsDFS(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + SubsetsDFS(tests[0].arg1) + } +} + +// sorting [][]int{} +func sortOutput(output *[][]int) { + for i := range *output { + sort.Ints((*output)[i]) + } + sort.Slice(*output, func(i, j int) bool { + return lexicoOrder(&(*output)[i], &(*output)[j]) + }) +} + +func lexicoOrder(a, b *[]int) bool { + for i := 0; i < len(*a) && i < len(*b); i++ { + if (*a)[i] < (*b)[i] { + return true + } else if (*a)[i] > (*b)[i] { + return false + } + } + return len((*a)) < len((*b)) +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. -cover +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkMaxEnvelopes-8 7799131 160.3 ns/op 88 B/op 3 allocs/op +BenchmarkMaxEnvelopes2-8 5800399 195.6 ns/op 80 B/op 4 allocs/op +PASS +coverage: 96.0% of statements +ok LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes 3.726s +*/ diff --git a/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array.go b/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array.go new file mode 100644 index 000000000..60502bafe --- /dev/null +++ b/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array.go @@ -0,0 +1,26 @@ +package mergesortedarray + +func Merge(nums1 []int, m int, nums2 []int, n int) { + if m == 0 { + copy(nums1, nums2) + return + } + + num1Idx, num2Idx, tail := m-1, n-1, m+n-1 + // ๅพžๆฏไธ€ๅ€‹array็š„ๅพŒ้ข้–‹ๅง‹ๆฏ”่ผƒ, ไธฆๆ”พๅ…ฅๆœ€ๅพŒ้ข็š„ไฝๅญ. ้€™ๆจฃๅช่ฆ่ท‘ไธ€ๆฌก + for ; num1Idx >= 0 && num2Idx >= 0; tail-- { + if nums1[num1Idx] > nums2[num2Idx] { + nums1[tail] = nums1[num1Idx] + num1Idx-- + } else { + nums1[tail] = nums2[num2Idx] + num2Idx-- + } + } + + // ๅฐ‡ๅฐšๆœช่ท‘ๅฎŒ็š„่ฃœ้ฝŠ + for ; num2Idx > 0; tail-- { + nums1[tail] = nums2[num2Idx] + num2Idx-- + } +} diff --git a/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array_test.go b/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array_test.go new file mode 100644 index 000000000..40cad741e --- /dev/null +++ b/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array_test.go @@ -0,0 +1,33 @@ +package mergesortedarray + +import ( + "reflect" + "testing" +) + +func TestMerge(t *testing.T) { + + tests := []struct { + arg1 []int + arg2 int + arg3 []int + arg4 int + want []int + }{ + { + []int{1, 2, 3, 0, 0, 0}, + 3, + []int{2, 5, 6}, + 3, + []int{1, 2, 2, 3, 5, 6}, + }, + } + + for _, tt := range tests { + Merge(tt.arg1, tt.arg2, tt.arg3, tt.arg4) + if !reflect.DeepEqual(tt.arg1, tt.want) { + t.Errorf("got = %v, want = %v", tt.arg1, tt.want) + } + } + +} diff --git a/Leetcode/0088.Merge-Sorted-Array/index.html b/Leetcode/0088.Merge-Sorted-Array/index.html new file mode 100644 index 000000000..e28207321 --- /dev/null +++ b/Leetcode/0088.Merge-Sorted-Array/index.html @@ -0,0 +1,3839 @@ + + + + + + + 0088.Merge Sorted Array ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                          +
                                                                                                                                          + + + + + + + + +
                                                                                                                                          + +
                                                                                                                                          + +
                                                                                                                                          + + + + + + + + +
                                                                                                                                          +
                                                                                                                                          + +
                                                                                                                                          +
                                                                                                                                          + +
                                                                                                                                          + +

                                                                                                                                          88. Merge Sorted Array

                                                                                                                                          題目

                                                                                                                                          +

                                                                                                                                          Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

                                                                                                                                          +

                                                                                                                                          Note:

                                                                                                                                          +

                                                                                                                                          You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

                                                                                                                                          +

                                                                                                                                          Example:

                                                                                                                                          +

                                                                                                                                          Input: +nums1 = [1,2,3,0,0,0], m = 3 +nums2 = [2,5,6], n = 3

                                                                                                                                          +

                                                                                                                                          Output: [1,2,2,3,5,6] +Constraints:

                                                                                                                                          +

                                                                                                                                          -10^9 <= nums1[i], nums2[i] <= 10^9 +nums1.length == m + n +nums2.length == n

                                                                                                                                          +

                                                                                                                                          題目大意

                                                                                                                                          +

                                                                                                                                          合併兩個已經有序的數組,結果放在第一個數組中,第一個數組假設空間足夠大。要求算法時間複雜度足夠低。

                                                                                                                                          +

                                                                                                                                          解題思路

                                                                                                                                          +

                                                                                                                                          為了不大量移動元素,就要從2個數組長度之和的最後一個位置開始,依次選取兩個數組中大的數,從第一個數組的尾巴開始往頭放,只要循環一次以後,就生成了合併以後的數組了。

                                                                                                                                          +

                                                                                                                                          來源

                                                                                                                                          + +

                                                                                                                                          解答

                                                                                                                                          +

                                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array.go

                                                                                                                                          +
                                                                                                                                          package mergesortedarray
                                                                                                                                          +
                                                                                                                                          +func Merge(nums1 []int, m int, nums2 []int, n int) {
                                                                                                                                          +    if m == 0 {
                                                                                                                                          +        copy(nums1, nums2)
                                                                                                                                          +        return
                                                                                                                                          +    }
                                                                                                                                          +
                                                                                                                                          +    num1Idx, num2Idx, tail := m-1, n-1, m+n-1
                                                                                                                                          +    // 從每一個array的後面開始比較, 並放入最後面的位子. 這樣只要跑一次
                                                                                                                                          +    for ; num1Idx >= 0 && num2Idx >= 0; tail-- {
                                                                                                                                          +        if nums1[num1Idx] > nums2[num2Idx] {
                                                                                                                                          +            nums1[tail] = nums1[num1Idx]
                                                                                                                                          +            num1Idx--
                                                                                                                                          +        } else {
                                                                                                                                          +            nums1[tail] = nums2[num2Idx]
                                                                                                                                          +            num2Idx--
                                                                                                                                          +        }
                                                                                                                                          +    }
                                                                                                                                          +
                                                                                                                                          +    // 將尚未跑完的補齊
                                                                                                                                          +    for ; num2Idx > 0; tail-- {
                                                                                                                                          +        nums1[tail] = nums2[num2Idx]
                                                                                                                                          +        num2Idx--
                                                                                                                                          +    }
                                                                                                                                          +}
                                                                                                                                          +
                                                                                                                                          +
                                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                          + +
                                                                                                                                          + +
                                                                                                                                          +
                                                                                                                                          +
                                                                                                                                          + +

                                                                                                                                          results matching ""

                                                                                                                                          +
                                                                                                                                            + +
                                                                                                                                            +
                                                                                                                                            + +

                                                                                                                                            No results matching ""

                                                                                                                                            + +
                                                                                                                                            +
                                                                                                                                            +
                                                                                                                                            + +
                                                                                                                                            +
                                                                                                                                            + +
                                                                                                                                            + + + + + + +
                                                                                                                                            + + +
                                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal.go b/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal.go new file mode 100644 index 000000000..efec72dcc --- /dev/null +++ b/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal.go @@ -0,0 +1,45 @@ +package binarytreeinordertraversal + +import ( + "LeetcodeGolang/Utility/structures" +) + +type TreeNode = structures.TreeNode + +func InorderTraversalStack(root *TreeNode) []int { + var result []int + inorderStack(root, &result) + return result +} + +func InorderTraversalRecursion(root *TreeNode) []int { + var result []int + inorderRecursion(root, &result) + return result +} + +func inorderRecursion(root *TreeNode, r *[]int) { + if root != nil { + inorderRecursion(root.Left, r) + *r = append(*r, root.Val) + inorderRecursion(root.Right, r) + } +} + +func inorderStack(root *TreeNode, r *[]int) { + s := structures.NewArrayStack() + p := root + + for !s.IsEmpty() || p != nil { + if p != nil { + // ๆŠŠไธญ้–“ๆ”พๅ…ฅstack, ๅพ€ๅทฆ็ฏ€้ปž็นผ็บŒๅพ€ไธ‹ๆ‰พ + s.Push(p) + p = p.Left + } else { + // ๆ‰พไธๅˆฐๆ™‚,ๅฐๅ‡บ + tmp := s.Pop().(*TreeNode) + *r = append(*r, tmp.Val) + p = tmp.Right + } + } +} diff --git a/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal_test.go b/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal_test.go new file mode 100644 index 000000000..27f58c303 --- /dev/null +++ b/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal_test.go @@ -0,0 +1,71 @@ +package binarytreeinordertraversal + +import ( + "LeetcodeGolang/Utility/structures" + "reflect" + "testing" +) + +func TestInorderTraversalStack(t *testing.T) { + + tests := []struct { + arg1 []int + want []int + }{ + { + arg1: []int{1, structures.NULL, 2, 3}, + want: []int{1, 3, 2}, + }, + } + + for _, tt := range tests { + root := structures.Ints2TreeNode(tt.arg1) + if got := InorderTraversalStack(root); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", tt.arg1, tt.want) + } + } +} + +func TestInorderTraversalRecursion(t *testing.T) { + + tests := []struct { + arg1 []int + want []int + }{ + { + arg1: []int{1, structures.NULL, 2, 3}, + want: []int{1, 3, 2}, + }, + } + + for _, tt := range tests { + root := structures.Ints2TreeNode(tt.arg1) + if got := InorderTraversalRecursion(root); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", tt.arg1, tt.want) + } + } +} + +func BenchmarkInorderTraversalStack(b *testing.B) { + arg1 := []int{1, structures.NULL, 2, 3} + root := structures.Ints2TreeNode(arg1) + b.ResetTimer() + for i := 0; i < b.N; i++ { + InorderTraversalStack(root) + } +} + +func BenchmarkInorderTraversalRecursion(b *testing.B) { + arg1 := []int{1, structures.NULL, 2, 3} + root := structures.Ints2TreeNode(arg1) + b.ResetTimer() + for i := 0; i < b.N; i++ { + InorderTraversalRecursion(root) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0094.Binary-Tree-Inorder-Traversal -bench=. +BenchmarkInorderTraversalStack-8 4469162 267.9 ns/op 568 B/op 4 allocs/op +BenchmarkInorderTraversalRecursion-8 11604469 103.4 ns/op 56 B/op 3 allocs/op +*/ diff --git a/Leetcode/0094.Binary-Tree-Inorder-Traversal/index.html b/Leetcode/0094.Binary-Tree-Inorder-Traversal/index.html new file mode 100644 index 000000000..51a12e106 --- /dev/null +++ b/Leetcode/0094.Binary-Tree-Inorder-Traversal/index.html @@ -0,0 +1,3863 @@ + + + + + + + 0094.Binary Tree Inorder Traversal ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                            +
                                                                                                                                            + + + + + + + + +
                                                                                                                                            + +
                                                                                                                                            + +
                                                                                                                                            + + + + + + + + +
                                                                                                                                            +
                                                                                                                                            + +
                                                                                                                                            +
                                                                                                                                            + +
                                                                                                                                            + +

                                                                                                                                            94. Binary Tree Inorder Traversal

                                                                                                                                            題目

                                                                                                                                            +

                                                                                                                                            Given a binary tree, return the inorder traversal of its nodes' values.

                                                                                                                                            +

                                                                                                                                            Example :

                                                                                                                                            +
                                                                                                                                            Input: [1,null,2,3]
                                                                                                                                            +   1
                                                                                                                                            +    \
                                                                                                                                            +     2
                                                                                                                                            +    /
                                                                                                                                            +   3
                                                                                                                                            +
                                                                                                                                            +Output: [1,3,2]
                                                                                                                                            +
                                                                                                                                            +

                                                                                                                                            Follow up: Recursive solution is trivial, could you do it iteratively?

                                                                                                                                            +

                                                                                                                                            題目大意

                                                                                                                                            +

                                                                                                                                            中序遍歷一顆樹

                                                                                                                                            +

                                                                                                                                            解題思路

                                                                                                                                            +

                                                                                                                                            深度優先 中序遍歷 + 若二元樹為空回傳空, 否則從根結點開始, 先走訪根節點的左子樹 -> 根節點 -> 右子樹 +深度優先, 前序遍歷 + 若二元樹為空回傳空, 否則先根節點-> 左子樹 -> 右子樹 +深度優先, 後序遍歷 + 若二元樹為空回傳空, 否則從左到右誒並從葉子節點後續走訪左子樹到右子樹, 最後是拜訪根節點

                                                                                                                                            +

                                                                                                                                            來源

                                                                                                                                            + +

                                                                                                                                            解答

                                                                                                                                            +

                                                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal.go

                                                                                                                                            +
                                                                                                                                            package binarytreeinordertraversal
                                                                                                                                            +
                                                                                                                                            +import (
                                                                                                                                            +    "LeetcodeGolang/Utility/structures"
                                                                                                                                            +)
                                                                                                                                            +
                                                                                                                                            +type TreeNode = structures.TreeNode
                                                                                                                                            +
                                                                                                                                            +func InorderTraversalStack(root *TreeNode) []int {
                                                                                                                                            +    var result []int
                                                                                                                                            +    inorderStack(root, &result)
                                                                                                                                            +    return result
                                                                                                                                            +}
                                                                                                                                            +
                                                                                                                                            +func InorderTraversalRecursion(root *TreeNode) []int {
                                                                                                                                            +    var result []int
                                                                                                                                            +    inorderRecursion(root, &result)
                                                                                                                                            +    return result
                                                                                                                                            +}
                                                                                                                                            +
                                                                                                                                            +func inorderRecursion(root *TreeNode, r *[]int) {
                                                                                                                                            +    if root != nil {
                                                                                                                                            +        inorderRecursion(root.Left, r)
                                                                                                                                            +        *r = append(*r, root.Val)
                                                                                                                                            +        inorderRecursion(root.Right, r)
                                                                                                                                            +    }
                                                                                                                                            +}
                                                                                                                                            +
                                                                                                                                            +func inorderStack(root *TreeNode, r *[]int) {
                                                                                                                                            +    s := structures.NewArrayStack()
                                                                                                                                            +    p := root
                                                                                                                                            +
                                                                                                                                            +    for !s.IsEmpty() || p != nil {
                                                                                                                                            +        if p != nil {
                                                                                                                                            +            // 把中間放入stack, 往左節點繼續往下找
                                                                                                                                            +            s.Push(p)
                                                                                                                                            +            p = p.Left
                                                                                                                                            +        } else {
                                                                                                                                            +            // 找不到時,印出
                                                                                                                                            +            tmp := s.Pop().(*TreeNode)
                                                                                                                                            +            *r = append(*r, tmp.Val)
                                                                                                                                            +            p = tmp.Right
                                                                                                                                            +        }
                                                                                                                                            +    }
                                                                                                                                            +}
                                                                                                                                            +
                                                                                                                                            +
                                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                            + +
                                                                                                                                            + +
                                                                                                                                            +
                                                                                                                                            +
                                                                                                                                            + +

                                                                                                                                            results matching ""

                                                                                                                                            +
                                                                                                                                              + +
                                                                                                                                              +
                                                                                                                                              + +

                                                                                                                                              No results matching ""

                                                                                                                                              + +
                                                                                                                                              +
                                                                                                                                              +
                                                                                                                                              + +
                                                                                                                                              +
                                                                                                                                              + +
                                                                                                                                              + + + + + + +
                                                                                                                                              + + +
                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0100.Same-Tree/ex1.jpg b/Leetcode/0100.Same-Tree/ex1.jpg new file mode 100644 index 000000000..6d9d16f36 Binary files /dev/null and b/Leetcode/0100.Same-Tree/ex1.jpg differ diff --git a/Leetcode/0100.Same-Tree/ex2.jpg b/Leetcode/0100.Same-Tree/ex2.jpg new file mode 100644 index 000000000..aff121eb5 Binary files /dev/null and b/Leetcode/0100.Same-Tree/ex2.jpg differ diff --git a/Leetcode/0100.Same-Tree/ex3.jpg b/Leetcode/0100.Same-Tree/ex3.jpg new file mode 100644 index 000000000..b69b001e0 Binary files /dev/null and b/Leetcode/0100.Same-Tree/ex3.jpg differ diff --git a/Leetcode/0100.Same-Tree/index.html b/Leetcode/0100.Same-Tree/index.html new file mode 100644 index 000000000..95e3a8b6e --- /dev/null +++ b/Leetcode/0100.Same-Tree/index.html @@ -0,0 +1,3859 @@ + + + + + + + 100. Same Tree ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                              +
                                                                                                                                              + + + + + + + + +
                                                                                                                                              + +
                                                                                                                                              + +
                                                                                                                                              + + + + + + + + +
                                                                                                                                              +
                                                                                                                                              + +
                                                                                                                                              +
                                                                                                                                              + +
                                                                                                                                              + +

                                                                                                                                              100. Same Tree

                                                                                                                                              題目

                                                                                                                                              +

                                                                                                                                              Given the roots of two binary trees p and q, write a function to check if they are the same or not.

                                                                                                                                              +

                                                                                                                                              Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

                                                                                                                                              +

                                                                                                                                              Example 1: +

                                                                                                                                              +

                                                                                                                                              Input: p = [1,2,3], q = [1,2,3] +Output: true

                                                                                                                                              +

                                                                                                                                              Example 2: +

                                                                                                                                              +

                                                                                                                                              Input: p = [1,2], q = [1,null,2] +Output: false

                                                                                                                                              +

                                                                                                                                              Example 3: +

                                                                                                                                              +

                                                                                                                                              Input: p = [1,2,1], q = [1,1,2] +Output: false

                                                                                                                                              +

                                                                                                                                              Constraints:

                                                                                                                                              +

                                                                                                                                              The number of nodes in both trees is in the range [0, 100]. +-104 <= Node.val <= 104

                                                                                                                                              +
                                                                                                                                                +
                                                                                                                                              • Accepted: 1.8M
                                                                                                                                              • +
                                                                                                                                              • Submissions: 3.1M
                                                                                                                                              • +
                                                                                                                                              • Acceptance Rate: 60.3%
                                                                                                                                              • +
                                                                                                                                              +

                                                                                                                                              題目大意

                                                                                                                                              +

                                                                                                                                              判斷 2 顆樹是否是完全相等的

                                                                                                                                              +

                                                                                                                                              解題思路

                                                                                                                                              +

                                                                                                                                              遞歸判斷即可

                                                                                                                                              +

                                                                                                                                              Big O

                                                                                                                                              +

                                                                                                                                              時間複雜 : O(n) +空間複雜 : O(1)

                                                                                                                                              +

                                                                                                                                              來源

                                                                                                                                              + +

                                                                                                                                              解答

                                                                                                                                              +

                                                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0100.Same-Tree/main.go

                                                                                                                                              +
                                                                                                                                              package sametree
                                                                                                                                              +
                                                                                                                                              +import "LeetcodeGolang/structures"
                                                                                                                                              +
                                                                                                                                              +/**
                                                                                                                                              + * Definition for a binary tree node.
                                                                                                                                              + * type TreeNode struct {
                                                                                                                                              + *     Val int
                                                                                                                                              + *     Left *TreeNode
                                                                                                                                              + *     Right *TreeNode
                                                                                                                                              + * }
                                                                                                                                              + */
                                                                                                                                              +
                                                                                                                                              +type TreeNode = structures.TreeNode
                                                                                                                                              +
                                                                                                                                              +// 時間複雜 O(n), 空間複雜 O(1)
                                                                                                                                              +func IsSameTree(p *TreeNode, q *TreeNode) bool {
                                                                                                                                              +    if p == nil && q == nil {
                                                                                                                                              +        return true
                                                                                                                                              +    } else if p != nil && q != nil {
                                                                                                                                              +        if p.Val == q.Val {
                                                                                                                                              +            return IsSameTree(p.Left, q.Left) && IsSameTree(p.Right, q.Right)
                                                                                                                                              +        }
                                                                                                                                              +        return false
                                                                                                                                              +    } else {
                                                                                                                                              +        return false
                                                                                                                                              +    }
                                                                                                                                              +}
                                                                                                                                              +
                                                                                                                                              +

                                                                                                                                              Benchmark

                                                                                                                                              +
                                                                                                                                              
                                                                                                                                              +
                                                                                                                                              +
                                                                                                                                              +
                                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                              + +
                                                                                                                                              + +
                                                                                                                                              +
                                                                                                                                              +
                                                                                                                                              + +

                                                                                                                                              results matching ""

                                                                                                                                              +
                                                                                                                                                + +
                                                                                                                                                +
                                                                                                                                                + +

                                                                                                                                                No results matching ""

                                                                                                                                                + +
                                                                                                                                                +
                                                                                                                                                +
                                                                                                                                                + +
                                                                                                                                                +
                                                                                                                                                + +
                                                                                                                                                + + + + + + +
                                                                                                                                                + + +
                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0100.Same-Tree/main.go b/Leetcode/0100.Same-Tree/main.go new file mode 100644 index 000000000..17296b01a --- /dev/null +++ b/Leetcode/0100.Same-Tree/main.go @@ -0,0 +1,28 @@ +package sametree + +import "LeetcodeGolang/structures" + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +type TreeNode = structures.TreeNode + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +func IsSameTree(p *TreeNode, q *TreeNode) bool { + if p == nil && q == nil { + return true + } else if p != nil && q != nil { + if p.Val == q.Val { + return IsSameTree(p.Left, q.Left) && IsSameTree(p.Right, q.Right) + } + return false + } else { + return false + } +} diff --git a/Leetcode/0100.Same-Tree/main_test.go b/Leetcode/0100.Same-Tree/main_test.go new file mode 100644 index 000000000..1af502ede --- /dev/null +++ b/Leetcode/0100.Same-Tree/main_test.go @@ -0,0 +1,54 @@ +package sametree + +import ( + "LeetcodeGolang/structures" + "testing" +) + +var tests = []struct { + arg1 []int + arg2 []int + want bool +}{ + { + []int{1, 2, 3}, + []int{1, 2, 3}, + true, + }, + { + []int{1, 2}, + []int{1, structures.NULL, 2}, + false, + }, + { + []int{1, 2, 1}, + []int{1, 1, 2}, + false, + }, +} + +func TestIsSameTree(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + p := structures.Ints2TreeNode(tt.arg1) + q := structures.Ints2TreeNode(tt.arg2) + + if got := IsSameTree(p, q); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkIsSameTree(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + p := structures.Ints2TreeNode(tests[0].arg1) + q := structures.Ints2TreeNode(tests[0].arg2) + IsSameTree(p, q) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0104.Maximum-Depth-of-Binary-Tree/index.html b/Leetcode/0104.Maximum-Depth-of-Binary-Tree/index.html new file mode 100644 index 000000000..45b331196 --- /dev/null +++ b/Leetcode/0104.Maximum-Depth-of-Binary-Tree/index.html @@ -0,0 +1,3820 @@ + + + + + + + 0104.Maximum Depth of Binary Tree ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                +
                                                                                                                                                + + + + + + + + +
                                                                                                                                                + +
                                                                                                                                                + +
                                                                                                                                                + + + + + + + + +
                                                                                                                                                +
                                                                                                                                                + +
                                                                                                                                                +
                                                                                                                                                + +
                                                                                                                                                + +

                                                                                                                                                0104.Maximum Depth of Binary Tree

                                                                                                                                                題目

                                                                                                                                                +

                                                                                                                                                Given the root of a binary tree, return its maximum depth.

                                                                                                                                                +

                                                                                                                                                A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

                                                                                                                                                +

                                                                                                                                                Example 1: +

                                                                                                                                                +

                                                                                                                                                Input: root = [3,9,20,null,null,15,7] +Output: 3 +Example 2:

                                                                                                                                                +

                                                                                                                                                Input: root = [1,null,2] +Output: 2

                                                                                                                                                +

                                                                                                                                                Constraints:

                                                                                                                                                +

                                                                                                                                                The number of nodes in the tree is in the range [0, 104]. +-100 <= Node.val <= 100

                                                                                                                                                +

                                                                                                                                                Accepted 2.7M Submissions 3.6M Acceptance Rate 74.7%

                                                                                                                                                +

                                                                                                                                                題目大意

                                                                                                                                                +

                                                                                                                                                解題思路

                                                                                                                                                +

                                                                                                                                                Big O

                                                                                                                                                +

                                                                                                                                                時間複雜 : 空間複雜 :

                                                                                                                                                +

                                                                                                                                                來源

                                                                                                                                                + +

                                                                                                                                                解答

                                                                                                                                                +

                                                                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main.go

                                                                                                                                                +
                                                                                                                                                
                                                                                                                                                +
                                                                                                                                                +
                                                                                                                                                +

                                                                                                                                                Benchmark

                                                                                                                                                +
                                                                                                                                                
                                                                                                                                                +
                                                                                                                                                +
                                                                                                                                                +
                                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                + +
                                                                                                                                                + +
                                                                                                                                                +
                                                                                                                                                +
                                                                                                                                                + +

                                                                                                                                                results matching ""

                                                                                                                                                +
                                                                                                                                                  + +
                                                                                                                                                  +
                                                                                                                                                  + +

                                                                                                                                                  No results matching ""

                                                                                                                                                  + +
                                                                                                                                                  +
                                                                                                                                                  +
                                                                                                                                                  + +
                                                                                                                                                  +
                                                                                                                                                  + +
                                                                                                                                                  + + + + + + +
                                                                                                                                                  + + +
                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main.go b/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main.go new file mode 100644 index 000000000..064dd40f1 --- /dev/null +++ b/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main.go @@ -0,0 +1,47 @@ +package maximumdepthofbinarytree + +import ( + "LeetcodeGolang/structures" + "math" +) + +type TreeNode = structures.TreeNode + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +func MaxDepth(root *TreeNode) int { + if root == nil { + return 0 + } + return int(math.Max(float64(MaxDepth(root.Left)), float64(MaxDepth(root.Right)))) + 1 + +} + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +func MaxDepthKimi(root *TreeNode) int { + count := 0 + return depth(root, count) + +} + +func depth(root *TreeNode, count int) int { + if root != nil { + count++ + countL := depth(root.Left, count) + countR := depth(root.Right, count) + if countL > countR { + count = countL + } else { + count = countR + } + } + return count +} diff --git a/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main_test.go b/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main_test.go new file mode 100644 index 000000000..97a5e3a87 --- /dev/null +++ b/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main_test.go @@ -0,0 +1,49 @@ +package maximumdepthofbinarytree + +import ( + "LeetcodeGolang/structures" + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{3, 9, 20, 0, 0, 15, 7}, + 3, + }, +} + +func TestMaxDepth(t *testing.T) { + for _, tt := range tests { + root := structures.Ints2TreeNode(tt.arg1) + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MaxDepth(root); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMaxDepthKimi(t *testing.T) { + for _, tt := range tests { + root := structures.Ints2TreeNode(tt.arg1) + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MaxDepthKimi(root); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkMaxDepth(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + root := structures.Ints2TreeNode(tests[0].arg1) + MaxDepth(root) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/105.construct Binary Tree From Preorder And In order Traversal-2.jpg b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/105.construct Binary Tree From Preorder And In order Traversal-2.jpg new file mode 100644 index 000000000..b1b8d717e Binary files /dev/null and b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/105.construct Binary Tree From Preorder And In order Traversal-2.jpg differ diff --git a/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/index.html b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/index.html new file mode 100644 index 000000000..67a3aaf67 --- /dev/null +++ b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/index.html @@ -0,0 +1,3841 @@ + + + + + + + 105. Construct Binary Tree from Preorder and Inorder Traversal ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                  +
                                                                                                                                                  + + + + + + + + +
                                                                                                                                                  + +
                                                                                                                                                  + +
                                                                                                                                                  + + + + + + + + +
                                                                                                                                                  +
                                                                                                                                                  + +
                                                                                                                                                  +
                                                                                                                                                  + +
                                                                                                                                                  + +

                                                                                                                                                  105. Construct Binary Tree from Preorder and Inorder Traversal

                                                                                                                                                  題目

                                                                                                                                                  +

                                                                                                                                                  題目大意

                                                                                                                                                  +

                                                                                                                                                  解題思路

                                                                                                                                                  +

                                                                                                                                                  Big O

                                                                                                                                                  +
                                                                                                                                                    +
                                                                                                                                                  • 時間複雜 : O(n) +n個樹節點

                                                                                                                                                    +
                                                                                                                                                  • +
                                                                                                                                                  • 空間複雜 : O(n) +遞迴調用的Stack空間是 O(h),其中 h 是樹的高度。 +在每個遞迴層級中,都創建了一個 TreeNode 對象,因此空間複雜度也是 O(n),其中 n 是節點的數量。 +h< n所以空間複雜為 O(n)

                                                                                                                                                    +
                                                                                                                                                  • +
                                                                                                                                                  +

                                                                                                                                                  來源

                                                                                                                                                  + +

                                                                                                                                                  解答

                                                                                                                                                  +

                                                                                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main.go

                                                                                                                                                  +
                                                                                                                                                  /**
                                                                                                                                                  + * Definition for a binary tree node.
                                                                                                                                                  + * type TreeNode struct {
                                                                                                                                                  + *     Val int
                                                                                                                                                  + *     Left *TreeNode
                                                                                                                                                  + *     Right *TreeNode
                                                                                                                                                  + * }
                                                                                                                                                  + */
                                                                                                                                                  +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                  +func buildTree(preorder []int, inorder []int) *TreeNode {
                                                                                                                                                  +    if len(preorder) == 0 {
                                                                                                                                                  +        return nil
                                                                                                                                                  +    }
                                                                                                                                                  +    result := &TreeNode{preorder[0], nil, nil}
                                                                                                                                                  +
                                                                                                                                                  +    i := 0
                                                                                                                                                  +    for ; i < len(inorder); i++ {
                                                                                                                                                  +        if preorder[0] == inorder[i] {
                                                                                                                                                  +            break
                                                                                                                                                  +        }
                                                                                                                                                  +    }
                                                                                                                                                  +    result.Left = buildTree(preorder[1:i+1], inorder[:i])
                                                                                                                                                  +    result.Right = buildTree(preorder[i+1:], inorder[i+1:])
                                                                                                                                                  +
                                                                                                                                                  +    return result
                                                                                                                                                  +}
                                                                                                                                                  +
                                                                                                                                                  +

                                                                                                                                                  +

                                                                                                                                                  Benchmark

                                                                                                                                                  +
                                                                                                                                                  
                                                                                                                                                  +
                                                                                                                                                  +
                                                                                                                                                  +
                                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                  + +
                                                                                                                                                  + +
                                                                                                                                                  +
                                                                                                                                                  +
                                                                                                                                                  + +

                                                                                                                                                  results matching ""

                                                                                                                                                  +
                                                                                                                                                    + +
                                                                                                                                                    +
                                                                                                                                                    + +

                                                                                                                                                    No results matching ""

                                                                                                                                                    + +
                                                                                                                                                    +
                                                                                                                                                    +
                                                                                                                                                    + +
                                                                                                                                                    +
                                                                                                                                                    + +
                                                                                                                                                    + + + + + + +
                                                                                                                                                    + + +
                                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main.go b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main.go new file mode 100644 index 000000000..278788d7e --- /dev/null +++ b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main.go @@ -0,0 +1,28 @@ +package constructbinarytreefrompreorderandinordertraversal + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +func buildTree(preorder []int, inorder []int) *TreeNode { + if len(preorder) == 0 { + return nil + } + result := &TreeNode{preorder[0], nil, nil} + + i := 0 + for ; i < len(inorder); i++ { + if preorder[0] == inorder[i] { + break + } + } + result.Left = buildTree(preorder[1:i+1], inorder[:i]) + result.Right = buildTree(preorder[i+1:], inorder[i+1:]) + + return result +} diff --git a/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main_test.go b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main_test.go new file mode 100644 index 000000000..0788b7309 --- /dev/null +++ b/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main_test.go @@ -0,0 +1,34 @@ +package + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "bbbab", + 4, + }, +} + +func TestLongestPalindromeSubseq(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := LongestPalindromeSubseq(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubseq(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindromeSubseq(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0110.Balanced-Binary-Tree/balance_1.jpg b/Leetcode/0110.Balanced-Binary-Tree/balance_1.jpg new file mode 100644 index 000000000..fe2734074 Binary files /dev/null and b/Leetcode/0110.Balanced-Binary-Tree/balance_1.jpg differ diff --git a/Leetcode/0110.Balanced-Binary-Tree/balance_2.jpg b/Leetcode/0110.Balanced-Binary-Tree/balance_2.jpg new file mode 100644 index 000000000..3c84fb9c8 Binary files /dev/null and b/Leetcode/0110.Balanced-Binary-Tree/balance_2.jpg differ diff --git a/Leetcode/0110.Balanced-Binary-Tree/index.html b/Leetcode/0110.Balanced-Binary-Tree/index.html new file mode 100644 index 000000000..c3afe6096 --- /dev/null +++ b/Leetcode/0110.Balanced-Binary-Tree/index.html @@ -0,0 +1,3856 @@ + + + + + + + 110. Balanced Binary Tree ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                    +
                                                                                                                                                    + + + + + + + + +
                                                                                                                                                    + +
                                                                                                                                                    + +
                                                                                                                                                    + + + + + + + + +
                                                                                                                                                    +
                                                                                                                                                    + +
                                                                                                                                                    +
                                                                                                                                                    + +
                                                                                                                                                    + +

                                                                                                                                                    110. Balanced Binary Tree

                                                                                                                                                    題目

                                                                                                                                                    +

                                                                                                                                                    Given a binary tree, determine if it is +height-balanced +.

                                                                                                                                                    +

                                                                                                                                                    Example 1: +

                                                                                                                                                    +

                                                                                                                                                    Input: root = [3,9,20,null,null,15,7] +Output: true

                                                                                                                                                    +

                                                                                                                                                    Example 2: +

                                                                                                                                                    +

                                                                                                                                                    Input: root = [1,2,2,3,3,null,null,4,4] +Output: false +Example 3:

                                                                                                                                                    +

                                                                                                                                                    Input: root = [] +Output: true

                                                                                                                                                    +

                                                                                                                                                    Constraints:

                                                                                                                                                    +

                                                                                                                                                    The number of nodes in the tree is in the range [0, 5000]. +-104 <= Node.val <= 104

                                                                                                                                                    +

                                                                                                                                                    題目大意

                                                                                                                                                    +

                                                                                                                                                    判斷一棵樹是不是平衡二叉樹。 平衡二叉樹的定義是:樹中每個節點都滿足左右兩個子樹的高度差 <= 1 的這個條件。

                                                                                                                                                    +

                                                                                                                                                    解題思路

                                                                                                                                                    +

                                                                                                                                                    高度運算可使用 0104.Maximum-Depth-of-Binary-Tree

                                                                                                                                                    +

                                                                                                                                                    平衡二叉樹(Balanced Binary Tree)是一種二叉樹,其左右子樹的高度差不超過一的二叉樹。換句話說,對於樹中的每個節點,其左子樹和右子樹的高度差不得大於1。

                                                                                                                                                    +

                                                                                                                                                    平衡二叉樹的主要目的是確保樹的高度平衡,這有助於保持在最壞情況下的查找、插入和刪除操作的時間複雜度在O(log n)範圍內,其中n是樹中節點的數量。這種平衡性有助於確保樹的性能良好,並減少操作的平均時間複雜度。

                                                                                                                                                    +

                                                                                                                                                    Big O

                                                                                                                                                    +

                                                                                                                                                    時間複雜 : O(n) +空間複雜 : O(1)

                                                                                                                                                    +

                                                                                                                                                    來源

                                                                                                                                                    + +

                                                                                                                                                    解答

                                                                                                                                                    +

                                                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0110.Balanced-Binary-Tree/main.go

                                                                                                                                                    +
                                                                                                                                                    package balancedbinarytree
                                                                                                                                                    +
                                                                                                                                                    +import "LeetcodeGolang/structures"
                                                                                                                                                    +
                                                                                                                                                    +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                    +
                                                                                                                                                    +/**
                                                                                                                                                    + * Definition for a binary tree node.
                                                                                                                                                    + * type TreeNode struct {
                                                                                                                                                    + *     Val int
                                                                                                                                                    + *     Left *TreeNode
                                                                                                                                                    + *     Right *TreeNode
                                                                                                                                                    + * }
                                                                                                                                                    + */
                                                                                                                                                    +
                                                                                                                                                    +type TreeNode = structures.TreeNode
                                                                                                                                                    +
                                                                                                                                                    +func IsBalanced(root *TreeNode) bool {
                                                                                                                                                    +    if root == nil {
                                                                                                                                                    +        return true
                                                                                                                                                    +    }
                                                                                                                                                    +    leftHight := depth(root.Left)
                                                                                                                                                    +    rightHight := depth(root.Right)
                                                                                                                                                    +
                                                                                                                                                    +    return abs(leftHight-rightHight) <= 0="" 1="" &&="" isbalanced(root.left)="" isbalanced(root.right)="" }="" func="" depth(root="" *treenode)="" int="" {="" if="" root="=" nil="" return="" max(depth(root.left),="" depth(root.right))="" +="" abs(n="" int)="" n="" <="" -n="" max(a,="" b="" a=""> b {
                                                                                                                                                    +        return a
                                                                                                                                                    +    }
                                                                                                                                                    +    return b
                                                                                                                                                    +}
                                                                                                                                                    +
                                                                                                                                                    +

                                                                                                                                                    Benchmark

                                                                                                                                                    +
                                                                                                                                                    
                                                                                                                                                    +
                                                                                                                                                    +
                                                                                                                                                    +
                                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                    + +
                                                                                                                                                    + +
                                                                                                                                                    +
                                                                                                                                                    +
                                                                                                                                                    + +

                                                                                                                                                    results matching ""

                                                                                                                                                    +
                                                                                                                                                      + +
                                                                                                                                                      +
                                                                                                                                                      + +

                                                                                                                                                      No results matching ""

                                                                                                                                                      + +
                                                                                                                                                      +
                                                                                                                                                      +
                                                                                                                                                      + +
                                                                                                                                                      +
                                                                                                                                                      + +
                                                                                                                                                      + + + + + + +
                                                                                                                                                      + + +
                                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0110.Balanced-Binary-Tree/main.go b/Leetcode/0110.Balanced-Binary-Tree/main.go new file mode 100644 index 000000000..321fae47d --- /dev/null +++ b/Leetcode/0110.Balanced-Binary-Tree/main.go @@ -0,0 +1,48 @@ +package balancedbinarytree + +import "LeetcodeGolang/structures" + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +type TreeNode = structures.TreeNode + +// ๆ™‚้–“่ค‡้›œ : `O(n)` ; ็ฉบ้–“่ค‡้›œ : `O(1)` +func IsBalanced(root *TreeNode) bool { + if root == nil { + return true + } + leftHight := depth(root.Left) + rightHight := depth(root.Right) + + return abs(leftHight-rightHight) <= 1 && IsBalanced(root.Left) && IsBalanced(root.Right) +} + +func depth(root *TreeNode) int { + if root == nil { + return 0 + } + return max(depth(root.Left), depth(root.Right)) + 1 +} + +func abs(n int) int { + if n < 0 { + return -n + } + return n +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/Leetcode/0110.Balanced-Binary-Tree/main_test.go b/Leetcode/0110.Balanced-Binary-Tree/main_test.go new file mode 100644 index 000000000..429fe465a --- /dev/null +++ b/Leetcode/0110.Balanced-Binary-Tree/main_test.go @@ -0,0 +1,48 @@ +package balancedbinarytree + +import ( + "LeetcodeGolang/structures" + "testing" +) + +var tests = []struct { + arg1 []int + want bool +}{ + { + []int{1, 2, 2, 3, structures.NULL, structures.NULL, 3, 4, structures.NULL, structures.NULL, 4}, + false, + }, + { + []int{1, 2, 2, 3, structures.NULL, structures.NULL, 3, 4, structures.NULL, structures.NULL, 4}, + false, + }, + { + []int{3, 9, 20, structures.NULL, structures.NULL, 15, 7}, + true, + }, +} + +func TestIsBalanced(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + root := structures.Ints2TreeNode(tt.arg1) + + if got := IsBalanced(root); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkIsBalanced(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + root := structures.Ints2TreeNode(tests[0].arg1) + IsBalanced(root) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/index.html b/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/index.html new file mode 100644 index 000000000..d0d3734df --- /dev/null +++ b/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/index.html @@ -0,0 +1,3907 @@ + + + + + + + 0121.Best Time to Buy and Sell Stock ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                      +
                                                                                                                                                      + + + + + + + + +
                                                                                                                                                      + +
                                                                                                                                                      + +
                                                                                                                                                      + + + + + + + + +
                                                                                                                                                      +
                                                                                                                                                      + +
                                                                                                                                                      +
                                                                                                                                                      + +
                                                                                                                                                      + +

                                                                                                                                                      0121.Best Time to Buy and Sell Stock)

                                                                                                                                                      題目

                                                                                                                                                      +

                                                                                                                                                      You are given an array prices where prices[i] is the price of a given stock on the ith day.

                                                                                                                                                      +

                                                                                                                                                      You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

                                                                                                                                                      +

                                                                                                                                                      Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

                                                                                                                                                      +

                                                                                                                                                      Example 1:

                                                                                                                                                      +

                                                                                                                                                      Input: prices = [7,1,5,3,6,4] +Output: 5 +Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. +Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. +Example 2:

                                                                                                                                                      +

                                                                                                                                                      Input: prices = [7,6,4,3,1] +Output: 0 +Explanation: In this case, no transactions are done and the max profit = 0.

                                                                                                                                                      +

                                                                                                                                                      Constraints:

                                                                                                                                                      +

                                                                                                                                                      1 <= prices.length <= 105 +0 <= prices[i] <= 104 +Accepted +3,930,287 +Submissions +7,349,138

                                                                                                                                                      +

                                                                                                                                                      題目大意

                                                                                                                                                      +

                                                                                                                                                      解題思路

                                                                                                                                                      +

                                                                                                                                                      Big O

                                                                                                                                                      +

                                                                                                                                                      時間複雜 : O(n) +空間複雜 : O(1)

                                                                                                                                                      +

                                                                                                                                                      來源

                                                                                                                                                      + +

                                                                                                                                                      解答

                                                                                                                                                      +

                                                                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main.go

                                                                                                                                                      +
                                                                                                                                                      package besttimetobuyandsellstock
                                                                                                                                                      +
                                                                                                                                                      +type numbers interface {
                                                                                                                                                      +    int | int8 | int16 | int32 | int64 | float32 | float64
                                                                                                                                                      +}
                                                                                                                                                      +
                                                                                                                                                      +func max[T numbers](a T, b T) T {
                                                                                                                                                      +    if a > b {
                                                                                                                                                      +        return a
                                                                                                                                                      +    }
                                                                                                                                                      +    return b
                                                                                                                                                      +}
                                                                                                                                                      +
                                                                                                                                                      +// 時間複雜 O(n), 空間複雜 O(1)
                                                                                                                                                      +// Slide windows
                                                                                                                                                      +func MaxProfit(prices []int) int {
                                                                                                                                                      +    left, right := 0, 1
                                                                                                                                                      +    maxProfit := 0
                                                                                                                                                      +    for right < len(prices) {
                                                                                                                                                      +        if prices[left] < prices[right] {
                                                                                                                                                      +            profit := prices[right] - prices[left]
                                                                                                                                                      +            maxProfit = max(maxProfit, profit)
                                                                                                                                                      +        } else {
                                                                                                                                                      +            left = right
                                                                                                                                                      +        }
                                                                                                                                                      +        right++
                                                                                                                                                      +    }
                                                                                                                                                      +    return maxProfit
                                                                                                                                                      +}
                                                                                                                                                      +
                                                                                                                                                      +// 時間複雜 O(n), 空間複雜 O(1)
                                                                                                                                                      +// DP : 最佳解
                                                                                                                                                      +func MaxProfitDP(prices []int) int {
                                                                                                                                                      +
                                                                                                                                                      +    if len(prices) == 0 {
                                                                                                                                                      +        return 0
                                                                                                                                                      +    }
                                                                                                                                                      +
                                                                                                                                                      +    minPrice := prices[0] // 初始最低價格為第一天的價格
                                                                                                                                                      +    maxProfit := 0
                                                                                                                                                      +
                                                                                                                                                      +    for i := 1; i < len(prices); i++ {
                                                                                                                                                      +        // 如果當前價格比最低價格低,更新最低價格
                                                                                                                                                      +        if prices[i] < minPrice {
                                                                                                                                                      +            minPrice = prices[i]
                                                                                                                                                      +        } else {
                                                                                                                                                      +            // 否則計算當前價格賣出時的利潤,並更新最大利潤
                                                                                                                                                      +            profit := prices[i] - minPrice
                                                                                                                                                      +            if profit > maxProfit {
                                                                                                                                                      +                maxProfit = profit
                                                                                                                                                      +            }
                                                                                                                                                      +        }
                                                                                                                                                      +    }
                                                                                                                                                      +
                                                                                                                                                      +    return maxProfit
                                                                                                                                                      +}
                                                                                                                                                      +
                                                                                                                                                      +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                      +// DP
                                                                                                                                                      +func MaxProfitDP2(prices []int) int {
                                                                                                                                                      +    n := len(prices)
                                                                                                                                                      +    dp := make([][]int, n)
                                                                                                                                                      +    for i := 0; i < n; i++ {
                                                                                                                                                      +        dp[i] = make([]int, 2)
                                                                                                                                                      +        if i-1 == -1 {
                                                                                                                                                      +            // base case
                                                                                                                                                      +            dp[i][0] = 0
                                                                                                                                                      +            dp[i][1] = -prices[i]
                                                                                                                                                      +            continue
                                                                                                                                                      +        }
                                                                                                                                                      +        dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i])
                                                                                                                                                      +        dp[i][1] = max(dp[i-1][1], -prices[i])
                                                                                                                                                      +    }
                                                                                                                                                      +    return dp[n-1][0]
                                                                                                                                                      +}
                                                                                                                                                      +
                                                                                                                                                      +

                                                                                                                                                      Benchmark

                                                                                                                                                      +
                                                                                                                                                      goos: darwin
                                                                                                                                                      +goarch: amd64
                                                                                                                                                      +pkg: LeetcodeGolang/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock
                                                                                                                                                      +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                      +BenchmarkMaxProfit-8            208734571                8.156 ns/op           0 B/op          0 allocs/op
                                                                                                                                                      +BenchmarkMaxProfitDP-8          240880467                5.720 ns/op           0 B/op          0 allocs/op
                                                                                                                                                      +BenchmarkMaxProfitDP2-8          4095866               282.6 ns/op           240 B/op          7 allocs/op
                                                                                                                                                      +PASS
                                                                                                                                                      +ok      LeetcodeGolang/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock    6.732s
                                                                                                                                                      +
                                                                                                                                                      +
                                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                      + +
                                                                                                                                                      + +
                                                                                                                                                      +
                                                                                                                                                      +
                                                                                                                                                      + +

                                                                                                                                                      results matching ""

                                                                                                                                                      +
                                                                                                                                                        + +
                                                                                                                                                        +
                                                                                                                                                        + +

                                                                                                                                                        No results matching ""

                                                                                                                                                        + +
                                                                                                                                                        +
                                                                                                                                                        +
                                                                                                                                                        + +
                                                                                                                                                        +
                                                                                                                                                        + +
                                                                                                                                                        + + + + + + +
                                                                                                                                                        + + +
                                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main.go b/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main.go new file mode 100644 index 000000000..7477e5f4f --- /dev/null +++ b/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main.go @@ -0,0 +1,75 @@ +package besttimetobuyandsellstock + +type numbers interface { + int | int8 | int16 | int32 | int64 | float32 | float64 +} + +func max[T numbers](a T, b T) T { + if a > b { + return a + } + return b +} + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +// Slide windows +func MaxProfit(prices []int) int { + left, right := 0, 1 + maxProfit := 0 + for right < len(prices) { + if prices[left] < prices[right] { + profit := prices[right] - prices[left] + maxProfit = max(maxProfit, profit) + } else { + left = right + } + right++ + } + return maxProfit +} + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +// DP : ๆœ€ไฝณ่งฃ +func MaxProfitDP(prices []int) int { + + if len(prices) == 0 { + return 0 + } + + minPrice := prices[0] // ๅˆๅง‹ๆœ€ไฝŽๅƒนๆ ผ็‚บ็ฌฌไธ€ๅคฉ็š„ๅƒนๆ ผ + maxProfit := 0 + + for i := 1; i < len(prices); i++ { + // ๅฆ‚ๆžœ็•ถๅ‰ๅƒนๆ ผๆฏ”ๆœ€ไฝŽๅƒนๆ ผไฝŽ๏ผŒๆ›ดๆ–ฐๆœ€ไฝŽๅƒนๆ ผ + if prices[i] < minPrice { + minPrice = prices[i] + } else { + // ๅฆๅ‰‡่จˆ็ฎ—็•ถๅ‰ๅƒนๆ ผ่ณฃๅ‡บๆ™‚็š„ๅˆฉๆฝค๏ผŒไธฆๆ›ดๆ–ฐๆœ€ๅคงๅˆฉๆฝค + profit := prices[i] - minPrice + if profit > maxProfit { + maxProfit = profit + } + } + } + + return maxProfit +} + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +// DP +func MaxProfitDP2(prices []int) int { + n := len(prices) + dp := make([][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([]int, 2) + if i-1 == -1 { + // base case + dp[i][0] = 0 + dp[i][1] = -prices[i] + continue + } + dp[i][0] = max(dp[i-1][0], dp[i-1][1]+prices[i]) + dp[i][1] = max(dp[i-1][1], -prices[i]) + } + return dp[n-1][0] +} diff --git a/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main_test.go b/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main_test.go new file mode 100644 index 000000000..32fcc4043 --- /dev/null +++ b/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main_test.go @@ -0,0 +1,77 @@ +package besttimetobuyandsellstock + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{7, 1, 5, 3, 6, 4}, + 5, + }, + { + []int{7, 6, 4, 3, 1}, + 0, + }, +} + +func TestMaxProfit(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MaxProfit(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMaxProfitDP(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MaxProfitDP(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMaxProfitDP2(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MaxProfitDP2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkMaxProfit(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxProfit(tests[0].arg1) + } +} + +func BenchmarkMaxProfitDP(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxProfitDP(tests[0].arg1) + } +} + +func BenchmarkMaxProfitDP2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxProfitDP2(tests[0].arg1) + } +} + +/* +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkMaxProfit-8 208734571 8.156 ns/op 0 B/op 0 allocs/op +BenchmarkMaxProfitDP-8 240880467 5.720 ns/op 0 B/op 0 allocs/op +BenchmarkMaxProfitDP2-8 4095866 282.6 ns/op 240 B/op 7 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock 6.732s +*/ diff --git a/Leetcode/0125.Valid-Palindrome/index.html b/Leetcode/0125.Valid-Palindrome/index.html new file mode 100644 index 000000000..316628ebf --- /dev/null +++ b/Leetcode/0125.Valid-Palindrome/index.html @@ -0,0 +1,3869 @@ + + + + + + + 0125. Valid Palindrome ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                        +
                                                                                                                                                        + + + + + + + + +
                                                                                                                                                        + +
                                                                                                                                                        + +
                                                                                                                                                        + + + + + + + + +
                                                                                                                                                        +
                                                                                                                                                        + +
                                                                                                                                                        +
                                                                                                                                                        + +
                                                                                                                                                        + +

                                                                                                                                                        0125. 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.

                                                                                                                                                        +

                                                                                                                                                        題目大意

                                                                                                                                                        +

                                                                                                                                                        解題思路

                                                                                                                                                        +

                                                                                                                                                        左右指針

                                                                                                                                                        +

                                                                                                                                                        Big O

                                                                                                                                                        +

                                                                                                                                                        時間複雜 : O(n) +空間複雜 : O(1)

                                                                                                                                                        +

                                                                                                                                                        來源

                                                                                                                                                        + +

                                                                                                                                                        解答

                                                                                                                                                        +

                                                                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0125.Valid-Palindrome/main.go

                                                                                                                                                        +
                                                                                                                                                        package validpalindrome
                                                                                                                                                        +
                                                                                                                                                        +import (
                                                                                                                                                        +    "strings"
                                                                                                                                                        +    "unicode"
                                                                                                                                                        +)
                                                                                                                                                        +
                                                                                                                                                        +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                        +func IsPalindrome(s string) bool {
                                                                                                                                                        +    // 將字符轉成小寫,
                                                                                                                                                        +    s = strings.ToLower(s)
                                                                                                                                                        +
                                                                                                                                                        +    // 使用雙指針, 一左一右相向而行, 判斷回文
                                                                                                                                                        +    left, right := 0, len(s)-1
                                                                                                                                                        +    for left < right {
                                                                                                                                                        +        for left < right && !isChar(s[left]) {
                                                                                                                                                        +            left++
                                                                                                                                                        +        }
                                                                                                                                                        +        for left < right && !isChar(s[right]) {
                                                                                                                                                        +            right--
                                                                                                                                                        +        }
                                                                                                                                                        +        if s[left] != s[right] {
                                                                                                                                                        +            return false
                                                                                                                                                        +        }
                                                                                                                                                        +        left++
                                                                                                                                                        +        right--
                                                                                                                                                        +    }
                                                                                                                                                        +    return true
                                                                                                                                                        +}
                                                                                                                                                        +
                                                                                                                                                        +func isChar(c byte) bool {
                                                                                                                                                        +    if unicode.IsLetter(rune(c)) || unicode.IsDigit(rune(c)) {
                                                                                                                                                        +        return true
                                                                                                                                                        +    }
                                                                                                                                                        +    return false
                                                                                                                                                        +}
                                                                                                                                                        +
                                                                                                                                                        +func isCharAZ09(c byte) bool {
                                                                                                                                                        +    if ('a' 
                                                                                                                                                        +

                                                                                                                                                        Benchmark

                                                                                                                                                        +
                                                                                                                                                        goos: darwin
                                                                                                                                                        +goarch: amd64
                                                                                                                                                        +pkg: LeetcodeGolang/Leetcode/0125.Valid-Palindrome
                                                                                                                                                        +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                        +BenchmarkIsPalindrome-8                  3840048               552.2 ns/op            32 B/op          1 allocs/op
                                                                                                                                                        +BenchmarkIsPalindromeStrBuilder-8        3164848               439.0 ns/op            88 B/op          4 allocs/op
                                                                                                                                                        +PASS
                                                                                                                                                        +ok      LeetcodeGolang/Leetcode/0125.Valid-Palindrome   5.242s
                                                                                                                                                        +
                                                                                                                                                        +
                                                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                        + +
                                                                                                                                                        + +
                                                                                                                                                        +
                                                                                                                                                        +
                                                                                                                                                        + +

                                                                                                                                                        results matching ""

                                                                                                                                                        +
                                                                                                                                                          + +
                                                                                                                                                          +
                                                                                                                                                          + +

                                                                                                                                                          No results matching ""

                                                                                                                                                          + +
                                                                                                                                                          +
                                                                                                                                                          +
                                                                                                                                                          + +
                                                                                                                                                          +
                                                                                                                                                          + +
                                                                                                                                                          + + + + + + +
                                                                                                                                                          + + +
                                                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0125.Valid-Palindrome/main.go b/Leetcode/0125.Valid-Palindrome/main.go new file mode 100644 index 000000000..78f4824cf --- /dev/null +++ b/Leetcode/0125.Valid-Palindrome/main.go @@ -0,0 +1,69 @@ +package validpalindrome + +import ( + "strings" + "unicode" +) + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +func IsPalindrome(s string) bool { + // ๅฐ‡ๅญ—็ฌฆ่ฝ‰ๆˆๅฐๅฏซ, + s = strings.ToLower(s) + + // ไฝฟ็”จ้›™ๆŒ‡้‡, ไธ€ๅทฆไธ€ๅณ็›ธๅ‘่€Œ่กŒ, ๅˆคๆ–ทๅ›žๆ–‡ + left, right := 0, len(s)-1 + for left < right { + for left < right && !isChar(s[left]) { + left++ + } + for left < right && !isChar(s[right]) { + right-- + } + if s[left] != s[right] { + return false + } + left++ + right-- + } + return true +} + +func isChar(c byte) bool { + if unicode.IsLetter(rune(c)) || unicode.IsDigit(rune(c)) { + return true + } + return false +} + +func isCharAZ09(c byte) bool { + if ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') { + return true + } + return false +} + +func IsPalindromeStrBuilder(s string) bool { + s = strings.ToLower(s) + strLen := len(s) + // ๅฐ‡ๅญ—็ฌฆ่ฝ‰ๆˆๅฐๅฏซ, ไธฆๆฟพๆŽ‰็ฉบๆ ผๅ’Œๆจ™้ปž็ฌฆ่™Ÿ็ญ‰ๅญ—็ฌฆ + var sb strings.Builder + for i := 0; i < strLen; i++ { + c := rune(s[i]) + if unicode.IsLetter(c) || unicode.IsDigit(c) { + sb.WriteRune(c) + } + } + + sbStr := sb.String() + + // ไฝฟ็”จ้›™ๆŒ‡้‡, ไธ€ๅทฆไธ€ๅณ็›ธๅ‘่€Œ่กŒ, ๅˆคๆ–ทๅ›žๆ–‡ + left, right := 0, len(sbStr)-1 + for left < right { + if sbStr[left] != sbStr[right] { + return false + } + left++ + right-- + } + return true +} diff --git a/Leetcode/0125.Valid-Palindrome/main_test.go b/Leetcode/0125.Valid-Palindrome/main_test.go new file mode 100644 index 000000000..9eea4669f --- /dev/null +++ b/Leetcode/0125.Valid-Palindrome/main_test.go @@ -0,0 +1,48 @@ +package validpalindrome + +import "testing" + +var tests = []struct { + arg1 string + want bool +}{ + { + "A man, a plan, a canal: Panama", + true, + }, +} + +func TestIsPalindrome(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := IsPalindrome(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkIsPalindrome(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + IsPalindrome(tests[0].arg1) + } +} + +func BenchmarkIsPalindromeStrBuilder(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + IsPalindromeStrBuilder(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0125.Valid-Palindrome -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0125.Valid-Palindrome +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkIsPalindrome-8 3840048 552.2 ns/op 32 B/op 1 allocs/op +BenchmarkIsPalindromeStrBuilder-8 3164848 439.0 ns/op 88 B/op 4 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0125.Valid-Palindrome 5.242s +*/ diff --git a/Leetcode/0128.Longest-Consecutive-Sequence/index.html b/Leetcode/0128.Longest-Consecutive-Sequence/index.html new file mode 100644 index 000000000..bc0975f16 --- /dev/null +++ b/Leetcode/0128.Longest-Consecutive-Sequence/index.html @@ -0,0 +1,3831 @@ + + + + + + + 128. Longest Consecutive Sequence ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                          +
                                                                                                                                                          + + + + + + + + +
                                                                                                                                                          + +
                                                                                                                                                          + +
                                                                                                                                                          + + + + + + + + +
                                                                                                                                                          +
                                                                                                                                                          + +
                                                                                                                                                          +
                                                                                                                                                          + +
                                                                                                                                                          + +

                                                                                                                                                          128. Longest Consecutive Sequence

                                                                                                                                                          題目

                                                                                                                                                          +

                                                                                                                                                          給定一個未排序的整數數位列 nums ,找出數字連續的最長序列(不要求序列元素在原陣列中連續)的長度。 +請你設計並實現時間複雜度為 O(n) 的演演算法解決此問題。

                                                                                                                                                          +

                                                                                                                                                          題目大意

                                                                                                                                                          +

                                                                                                                                                          解題思路

                                                                                                                                                          +

                                                                                                                                                          Big O

                                                                                                                                                          +

                                                                                                                                                          時間複雜 : O(n) +空間複雜 : O(n)

                                                                                                                                                          +

                                                                                                                                                          來源

                                                                                                                                                          + +

                                                                                                                                                          解答

                                                                                                                                                          +

                                                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0128.Longest-Consecutive-Sequence/main.go

                                                                                                                                                          +
                                                                                                                                                          package longestconsecutivesequence
                                                                                                                                                          +
                                                                                                                                                          +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                          +func longestConsecutive(nums []int) int {
                                                                                                                                                          +    m := make(map[int]struct{}, len(nums))
                                                                                                                                                          +    for _, num := range nums {
                                                                                                                                                          +        m[num] = struct{}{}
                                                                                                                                                          +    }
                                                                                                                                                          +    result := 0
                                                                                                                                                          +    for v := range m {
                                                                                                                                                          +        // 如果沒找到該數字的前一個數字, 則把該數字刀做連續序列的第一個數
                                                                                                                                                          +        if _, ok := m[v-1]; !ok {
                                                                                                                                                          +            length := 1
                                                                                                                                                          +            for _, exit := m[v+length]; exit; _, exit = m[v+length] {
                                                                                                                                                          +                length++
                                                                                                                                                          +            }
                                                                                                                                                          +            if result < length {
                                                                                                                                                          +                result = length
                                                                                                                                                          +            }
                                                                                                                                                          +        }
                                                                                                                                                          +    }
                                                                                                                                                          +    return result
                                                                                                                                                          +}
                                                                                                                                                          +
                                                                                                                                                          +

                                                                                                                                                          Benchmark

                                                                                                                                                          +
                                                                                                                                                          
                                                                                                                                                          +
                                                                                                                                                          +
                                                                                                                                                          +
                                                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                          + +
                                                                                                                                                          + +
                                                                                                                                                          +
                                                                                                                                                          +
                                                                                                                                                          + +

                                                                                                                                                          results matching ""

                                                                                                                                                          +
                                                                                                                                                            + +
                                                                                                                                                            +
                                                                                                                                                            + +

                                                                                                                                                            No results matching ""

                                                                                                                                                            + +
                                                                                                                                                            +
                                                                                                                                                            +
                                                                                                                                                            + +
                                                                                                                                                            +
                                                                                                                                                            + +
                                                                                                                                                            + + + + + + +
                                                                                                                                                            + + +
                                                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0128.Longest-Consecutive-Sequence/main.go b/Leetcode/0128.Longest-Consecutive-Sequence/main.go new file mode 100644 index 000000000..e0d225207 --- /dev/null +++ b/Leetcode/0128.Longest-Consecutive-Sequence/main.go @@ -0,0 +1,23 @@ +package longestconsecutivesequence + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(n) +func longestConsecutive(nums []int) int { + m := make(map[int]struct{}, len(nums)) + for _, num := range nums { + m[num] = struct{}{} + } + result := 0 + for v := range m { + // ๅฆ‚ๆžœๆฒ’ๆ‰พๅˆฐ่ฉฒๆ•ธๅญ—็š„ๅ‰ไธ€ๅ€‹ๆ•ธๅญ—, ๅ‰‡ๆŠŠ่ฉฒๆ•ธๅญ—็•ถๅš้€ฃ็บŒๅบๅˆ—็š„็ฌฌไธ€ๅ€‹ๆ•ธ + if _, ok := m[v-1]; !ok { + length := 1 + for _, exit := m[v+length]; exit; _, exit = m[v+length] { + length++ + } + if result < length { + result = length + } + } + } + return result +} diff --git a/Leetcode/0128.Longest-Consecutive-Sequence/main_test.go b/Leetcode/0128.Longest-Consecutive-Sequence/main_test.go new file mode 100644 index 000000000..da9202b6a --- /dev/null +++ b/Leetcode/0128.Longest-Consecutive-Sequence/main_test.go @@ -0,0 +1,34 @@ +package longestconsecutivesequence + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{100, 4, 200, 1, 3, 2}, + 4, + }, +} + +func TestLongestConsecutive(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := longestConsecutive(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestConsecutive(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + longestConsecutive(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0138.Copy-List-with-Random-Pointer/index.html b/Leetcode/0138.Copy-List-with-Random-Pointer/index.html new file mode 100644 index 000000000..fec2d8150 --- /dev/null +++ b/Leetcode/0138.Copy-List-with-Random-Pointer/index.html @@ -0,0 +1,3865 @@ + + + + + + + 138. Copy List with Random Pointer ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                            +
                                                                                                                                                            + + + + + + + + +
                                                                                                                                                            + +
                                                                                                                                                            + +
                                                                                                                                                            + + + + + + + + +
                                                                                                                                                            +
                                                                                                                                                            + +
                                                                                                                                                            +
                                                                                                                                                            + +
                                                                                                                                                            + +

                                                                                                                                                            138. Copy List with Random Pointer

                                                                                                                                                            題目

                                                                                                                                                            +

                                                                                                                                                            題目大意

                                                                                                                                                            +

                                                                                                                                                            解題思路

                                                                                                                                                            +

                                                                                                                                                            對於數據結構複製,甭管他怎麼變,你就記住最簡單的方式:一個哈希表 + 兩次遍歷

                                                                                                                                                            +
                                                                                                                                                              +
                                                                                                                                                            • 第一次遍歷專門clone節點,藉助 Hash表把原始節點和clone節點的映射存儲起來;
                                                                                                                                                            • +
                                                                                                                                                            • 第二次專門組裝節點,照著原數據結構的樣子,把clone節點的指標組裝起來。
                                                                                                                                                            • +
                                                                                                                                                            +

                                                                                                                                                            Big O

                                                                                                                                                            +
                                                                                                                                                              +
                                                                                                                                                            • 時間複雜 : O(n) ,其中 n 是鏈表的長度。 對於每個節點,我們至多訪問其「後繼節點」和「隨機指標指向的節點」各一次,均攤每個點至多被訪問兩次。
                                                                                                                                                            • +
                                                                                                                                                            • 空間複雜 : O(n) 其中 n 是鏈表的長度。 為哈希表的空間開銷
                                                                                                                                                            • +
                                                                                                                                                            +

                                                                                                                                                            來源

                                                                                                                                                            + +

                                                                                                                                                            解答

                                                                                                                                                            +

                                                                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0138.Copy-List-with-Random-Pointer/main.go

                                                                                                                                                            +
                                                                                                                                                            package copylistwithrandompointer
                                                                                                                                                            +
                                                                                                                                                            +/**
                                                                                                                                                            + * Definition for a Node.
                                                                                                                                                            + * type Node struct {
                                                                                                                                                            + *     Val int
                                                                                                                                                            + *     Next *Node
                                                                                                                                                            + *     Random *Node
                                                                                                                                                            + * }
                                                                                                                                                            + */
                                                                                                                                                            +
                                                                                                                                                            +var cacheMap map[*Node]*Node
                                                                                                                                                            +
                                                                                                                                                            +// 時間複雜 O(n), 空間複雜 O(n)
                                                                                                                                                            +func copyRandomList(head *Node) *Node {
                                                                                                                                                            +    cacheMap = make(map[*Node]*Node)
                                                                                                                                                            +    return deepCopy(head)
                                                                                                                                                            +}
                                                                                                                                                            +
                                                                                                                                                            +func deepCopy(node *Node) *Node {
                                                                                                                                                            +    if node == nil {
                                                                                                                                                            +        return nil
                                                                                                                                                            +    }
                                                                                                                                                            +    if n, ok := cacheMap[node]; ok {
                                                                                                                                                            +        return n
                                                                                                                                                            +    }
                                                                                                                                                            +    newNode := &Node{Val: node.Val}
                                                                                                                                                            +    cacheMap[node] = newNode
                                                                                                                                                            +    newNode.Next = deepCopy(node.Next)
                                                                                                                                                            +    newNode.Random = deepCopy(node.Random)
                                                                                                                                                            +    return newNode
                                                                                                                                                            +}
                                                                                                                                                            +
                                                                                                                                                            +func copyRandomList2(head *Node) *Node {
                                                                                                                                                            +    cMap := make(map[*Node]*Node)
                                                                                                                                                            +    cur := head
                                                                                                                                                            +    // 第一次遍歷專門clone節點,藉助 Hash表把原始節點和clone節點的映射存儲起來;
                                                                                                                                                            +    for cur != nil {
                                                                                                                                                            +        newNode := &Node{Val: cur.Val}
                                                                                                                                                            +        cMap[cur] = newNode
                                                                                                                                                            +        cur = cur.Next
                                                                                                                                                            +    }
                                                                                                                                                            +    // 第二次專門組裝節點,照著原數據結構的樣子,把clone節點的指標組裝起來。
                                                                                                                                                            +    newHead := cMap[head]
                                                                                                                                                            +    for head != nil {
                                                                                                                                                            +        node := cMap[head]
                                                                                                                                                            +        node.Next = cMap[head.Next]
                                                                                                                                                            +        node.Random = cMap[head.Random]
                                                                                                                                                            +        head = head.Next
                                                                                                                                                            +    }
                                                                                                                                                            +    return newHead
                                                                                                                                                            +}
                                                                                                                                                            +
                                                                                                                                                            +

                                                                                                                                                            Benchmark

                                                                                                                                                            +
                                                                                                                                                            
                                                                                                                                                            +
                                                                                                                                                            +
                                                                                                                                                            +
                                                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                            + +
                                                                                                                                                            + +
                                                                                                                                                            +
                                                                                                                                                            +
                                                                                                                                                            + +

                                                                                                                                                            results matching ""

                                                                                                                                                            +
                                                                                                                                                              + +
                                                                                                                                                              +
                                                                                                                                                              + +

                                                                                                                                                              No results matching ""

                                                                                                                                                              + +
                                                                                                                                                              +
                                                                                                                                                              +
                                                                                                                                                              + +
                                                                                                                                                              +
                                                                                                                                                              + +
                                                                                                                                                              + + + + + + +
                                                                                                                                                              + + +
                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0138.Copy-List-with-Random-Pointer/main.go b/Leetcode/0138.Copy-List-with-Random-Pointer/main.go new file mode 100644 index 000000000..5a96fb3b0 --- /dev/null +++ b/Leetcode/0138.Copy-List-with-Random-Pointer/main.go @@ -0,0 +1,52 @@ +package copylistwithrandompointer + +/** + * Definition for a Node. + * type Node struct { + * Val int + * Next *Node + * Random *Node + * } + */ + +var cacheMap map[*Node]*Node + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(n) +func copyRandomList(head *Node) *Node { + cacheMap = make(map[*Node]*Node) + return deepCopy(head) +} + +func deepCopy(node *Node) *Node { + if node == nil { + return nil + } + if n, ok := cacheMap[node]; ok { + return n + } + newNode := &Node{Val: node.Val} + cacheMap[node] = newNode + newNode.Next = deepCopy(node.Next) + newNode.Random = deepCopy(node.Random) + return newNode +} + +func copyRandomList2(head *Node) *Node { + cMap := make(map[*Node]*Node) + cur := head + // ็ฌฌไธ€ๆฌก้ๆญทๅฐˆ้–€clone็ฏ€้ปž๏ผŒ่—‰ๅŠฉ Hash่กจๆŠŠๅŽŸๅง‹็ฏ€้ปžๅ’Œclone็ฏ€้ปž็š„ๆ˜ ๅฐ„ๅญ˜ๅ„ฒ่ตทไพ†; + for cur != nil { + newNode := &Node{Val: cur.Val} + cMap[cur] = newNode + cur = cur.Next + } + // ็ฌฌไบŒๆฌกๅฐˆ้–€็ต„่ฃ็ฏ€้ปž๏ผŒ็…ง่‘—ๅŽŸๆ•ธๆ“š็ตๆง‹็š„ๆจฃๅญ๏ผŒๆŠŠclone็ฏ€้ปž็š„ๆŒ‡ๆจ™็ต„่ฃ่ตทไพ†ใ€‚ + newHead := cMap[head] + for head != nil { + node := cMap[head] + node.Next = cMap[head.Next] + node.Random = cMap[head.Random] + head = head.Next + } + return newHead +} diff --git a/Leetcode/0138.Copy-List-with-Random-Pointer/main_test.go b/Leetcode/0138.Copy-List-with-Random-Pointer/main_test.go new file mode 100644 index 000000000..0788b7309 --- /dev/null +++ b/Leetcode/0138.Copy-List-with-Random-Pointer/main_test.go @@ -0,0 +1,34 @@ +package + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "bbbab", + 4, + }, +} + +func TestLongestPalindromeSubseq(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := LongestPalindromeSubseq(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubseq(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindromeSubseq(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle.go b/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle.go new file mode 100644 index 000000000..6706a43d7 --- /dev/null +++ b/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle.go @@ -0,0 +1,19 @@ +package linkedlistcycle + +type ListNode struct { + Val int + Next *ListNode +} + +func HasCycle(head *ListNode) bool { + fast := head + slow := head + for slow != nil && fast != nil && fast.Next != nil { + fast = fast.Next.Next + slow = slow.Next + if slow == fast { + return true + } + } + return false +} diff --git a/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle_test.go b/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle_test.go new file mode 100644 index 000000000..1ba7da4e8 --- /dev/null +++ b/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle_test.go @@ -0,0 +1,29 @@ +package linkedlistcycle + +import "testing" + +func TestHasCycle(t *testing.T) { + a := &ListNode{1, nil} + b := &ListNode{2, nil} + c := &ListNode{3, nil} + // d := &ListNode{4, nil} + a.Next = b + b.Next = c + c.Next = a + + tests := []struct { + arg1 *ListNode + want bool + }{ + { + arg1: a, + want: true, + }, + } + + for _, tt := range tests { + if got := HasCycle(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Leetcode/0141.Linked-List-Cycle/index.html b/Leetcode/0141.Linked-List-Cycle/index.html new file mode 100644 index 000000000..37f5aed47 --- /dev/null +++ b/Leetcode/0141.Linked-List-Cycle/index.html @@ -0,0 +1,3823 @@ + + + + + + + 0141.Linked List Cycle ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                              +
                                                                                                                                                              + + + + + + + + +
                                                                                                                                                              + +
                                                                                                                                                              + +
                                                                                                                                                              + + + + + + + + +
                                                                                                                                                              +
                                                                                                                                                              + +
                                                                                                                                                              +
                                                                                                                                                              + +
                                                                                                                                                              + +

                                                                                                                                                              141. Linked List Cycle

                                                                                                                                                              題目

                                                                                                                                                              +

                                                                                                                                                              Given a linked list, determine if it has a cycle in it.

                                                                                                                                                              +

                                                                                                                                                              Follow up: +Can you solve it without using extra space?

                                                                                                                                                              +

                                                                                                                                                              題目大意

                                                                                                                                                              +

                                                                                                                                                              判斷鍊表是否有環,不能使用額外的空間。

                                                                                                                                                              +

                                                                                                                                                              解題思路

                                                                                                                                                              +

                                                                                                                                                              給 2 個指針,一個指針是另外一個指針的下一個指針。快指針一次走 2 格,慢指針一次走 1 格。如果存在環,那麼前一個指針一定會經過若干圈之後追上慢的指針。

                                                                                                                                                              +

                                                                                                                                                              來源

                                                                                                                                                              + +

                                                                                                                                                              解答

                                                                                                                                                              +

                                                                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle.go

                                                                                                                                                              +
                                                                                                                                                              package linkedlistcycle
                                                                                                                                                              +
                                                                                                                                                              +type ListNode struct {
                                                                                                                                                              +    Val  int
                                                                                                                                                              +    Next *ListNode
                                                                                                                                                              +}
                                                                                                                                                              +
                                                                                                                                                              +func HasCycle(head *ListNode) bool {
                                                                                                                                                              +    fast := head
                                                                                                                                                              +    slow := head
                                                                                                                                                              +    for slow != nil && fast != nil && fast.Next != nil {
                                                                                                                                                              +        fast = fast.Next.Next
                                                                                                                                                              +        slow = slow.Next
                                                                                                                                                              +        if slow == fast {
                                                                                                                                                              +            return true
                                                                                                                                                              +        }
                                                                                                                                                              +    }
                                                                                                                                                              +    return false
                                                                                                                                                              +}
                                                                                                                                                              +
                                                                                                                                                              +
                                                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                              + +
                                                                                                                                                              + +
                                                                                                                                                              +
                                                                                                                                                              +
                                                                                                                                                              + +

                                                                                                                                                              results matching ""

                                                                                                                                                              +
                                                                                                                                                                + +
                                                                                                                                                                +
                                                                                                                                                                + +

                                                                                                                                                                No results matching ""

                                                                                                                                                                + +
                                                                                                                                                                +
                                                                                                                                                                +
                                                                                                                                                                + +
                                                                                                                                                                +
                                                                                                                                                                + +
                                                                                                                                                                + + + + + + +
                                                                                                                                                                + + +
                                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0142.Linked-List-CycleII/index.html b/Leetcode/0142.Linked-List-CycleII/index.html new file mode 100644 index 000000000..78851f545 --- /dev/null +++ b/Leetcode/0142.Linked-List-CycleII/index.html @@ -0,0 +1,3858 @@ + + + + + + + 0142.Linked List Cycle II ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                +
                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                + +
                                                                                                                                                                + +
                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                +
                                                                                                                                                                + +
                                                                                                                                                                +
                                                                                                                                                                + +
                                                                                                                                                                + +

                                                                                                                                                                142. Linked List Cycle II

                                                                                                                                                                題目

                                                                                                                                                                +

                                                                                                                                                                Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.

                                                                                                                                                                +

                                                                                                                                                                There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter.

                                                                                                                                                                +

                                                                                                                                                                Do not modify the linked list.

                                                                                                                                                                +

                                                                                                                                                                Example 1: +

                                                                                                                                                                +
                                                                                                                                                                Input: head = [3,2,0,-4], pos = 1
                                                                                                                                                                +Output: tail connects to node index 1
                                                                                                                                                                +Explanation: There is a cycle in the linked list, where tail connects to the second node.
                                                                                                                                                                +

                                                                                                                                                                Example 2: +

                                                                                                                                                                +
                                                                                                                                                                Input: head = [1,2], pos = 0
                                                                                                                                                                +Output: tail connects to node index 0
                                                                                                                                                                +Explanation: There is a cycle in the linked list, where tail connects to the first node.
                                                                                                                                                                +

                                                                                                                                                                Example 3: +

                                                                                                                                                                +
                                                                                                                                                                Input: head = [1], pos = -1
                                                                                                                                                                +Output: no cycle
                                                                                                                                                                +Explanation: There is no cycle in the linked list.
                                                                                                                                                                +

                                                                                                                                                                Constraints:

                                                                                                                                                                +
                                                                                                                                                                  +
                                                                                                                                                                • The number of the nodes in the list is in the range [0, 104].
                                                                                                                                                                • +
                                                                                                                                                                • -105 <= Node.val <= 105
                                                                                                                                                                • +
                                                                                                                                                                • pos is -1 or a valid index in the linked-list.
                                                                                                                                                                • +
                                                                                                                                                                +

                                                                                                                                                                題目大意

                                                                                                                                                                +

                                                                                                                                                                已知linked list 中有含有環, 返回這個環的起始位置

                                                                                                                                                                +

                                                                                                                                                                解題思路

                                                                                                                                                                +

                                                                                                                                                                假設第一次相遇, slow 走了k步, 那麼 fast就走了 2k, 也就是說fast比slow多走了k步(環長度的整數倍) +設相遇點與環的起點距離為 m, 那麼環的起點Head的距離為 k-m +

                                                                                                                                                                +

                                                                                                                                                                來源

                                                                                                                                                                + +

                                                                                                                                                                解答

                                                                                                                                                                +

                                                                                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0142.Linked-List-CycleII/main.go

                                                                                                                                                                +
                                                                                                                                                                package linkedlistcycleII
                                                                                                                                                                +
                                                                                                                                                                +/**
                                                                                                                                                                + * Definition for singly-linked list.
                                                                                                                                                                + * type ListNode struct {
                                                                                                                                                                + *     Val int
                                                                                                                                                                + *     Next *ListNode
                                                                                                                                                                + * }
                                                                                                                                                                + */
                                                                                                                                                                +type ListNode struct {
                                                                                                                                                                +    Val  int
                                                                                                                                                                +    Next *ListNode
                                                                                                                                                                +}
                                                                                                                                                                +
                                                                                                                                                                +func DetectCycle(head *ListNode) *ListNode {
                                                                                                                                                                +    fast, slow := head, head
                                                                                                                                                                +    for fast != nil && fast.Next != nil {
                                                                                                                                                                +        fast = fast.Next.Next
                                                                                                                                                                +        slow = slow.Next
                                                                                                                                                                +        if slow == fast {
                                                                                                                                                                +            // 找到相遇點
                                                                                                                                                                +            break
                                                                                                                                                                +        }
                                                                                                                                                                +    }
                                                                                                                                                                +
                                                                                                                                                                +    slow = head
                                                                                                                                                                +    for slow != fast {
                                                                                                                                                                +        fast = fast.Next
                                                                                                                                                                +        slow = slow.Next
                                                                                                                                                                +    }
                                                                                                                                                                +    return slow
                                                                                                                                                                +}
                                                                                                                                                                +
                                                                                                                                                                +
                                                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                + +
                                                                                                                                                                + +
                                                                                                                                                                +
                                                                                                                                                                +
                                                                                                                                                                + +

                                                                                                                                                                results matching ""

                                                                                                                                                                +
                                                                                                                                                                  + +
                                                                                                                                                                  +
                                                                                                                                                                  + +

                                                                                                                                                                  No results matching ""

                                                                                                                                                                  + +
                                                                                                                                                                  +
                                                                                                                                                                  +
                                                                                                                                                                  + +
                                                                                                                                                                  +
                                                                                                                                                                  + +
                                                                                                                                                                  + + + + + + +
                                                                                                                                                                  + + +
                                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0142.Linked-List-CycleII/main.go b/Leetcode/0142.Linked-List-CycleII/main.go new file mode 100644 index 000000000..d1ff9950f --- /dev/null +++ b/Leetcode/0142.Linked-List-CycleII/main.go @@ -0,0 +1,33 @@ +package linkedlistcycleII + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +type ListNode struct { + Val int + Next *ListNode +} + +func DetectCycle(head *ListNode) *ListNode { + fast, slow := head, head + for fast != nil && fast.Next != nil { + fast = fast.Next.Next + slow = slow.Next + if slow == fast { + // ๆ‰พๅˆฐ็›ธ้‡้ปž + break + } + } + + slow = head + for slow != fast { + fast = fast.Next + slow = slow.Next + } + // ๅ…ฉๅ€‹ๆŒ‡้‡็›ธ้‡็š„้ปžๅฐฑๆ˜ฏ็’ฐ็š„่ตท้ปž + return slow +} diff --git a/Leetcode/0142.Linked-List-CycleII/main_test.go b/Leetcode/0142.Linked-List-CycleII/main_test.go new file mode 100644 index 000000000..a6e19444d --- /dev/null +++ b/Leetcode/0142.Linked-List-CycleII/main_test.go @@ -0,0 +1,43 @@ +package linkedlistcycleII + +import ( + "reflect" + "testing" +) + +func TestDetectCycle(t *testing.T) { + a := &ListNode{1, nil} + b := &ListNode{2, nil} + c := &ListNode{3, nil} + // d := &ListNode{4, nil} + a.Next = b + b.Next = c + c.Next = a + + d := &ListNode{1, nil} + e := &ListNode{2, nil} + f := &ListNode{3, nil} + d.Next = e + e.Next = f + f.Next = a + + tests := []struct { + arg1 *ListNode + want *ListNode + }{ + { + arg1: a, + want: a, + }, + { + arg1: d, + want: a, + }, + } + + for _, tt := range tests { + if got := DetectCycle(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Leetcode/0143.Reorder-List/index.html b/Leetcode/0143.Reorder-List/index.html new file mode 100644 index 000000000..2abe89349 --- /dev/null +++ b/Leetcode/0143.Reorder-List/index.html @@ -0,0 +1,3861 @@ + + + + + + + 143. Reorder List ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                  +
                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                  + +
                                                                                                                                                                  + +
                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                  +
                                                                                                                                                                  + +
                                                                                                                                                                  +
                                                                                                                                                                  + +
                                                                                                                                                                  + +

                                                                                                                                                                  143. Reorder List

                                                                                                                                                                  題目

                                                                                                                                                                  +

                                                                                                                                                                  題目大意

                                                                                                                                                                  +

                                                                                                                                                                  解題思路

                                                                                                                                                                  +

                                                                                                                                                                  Big O

                                                                                                                                                                  +
                                                                                                                                                                    +
                                                                                                                                                                  • 時間複雜 : ``
                                                                                                                                                                  • +
                                                                                                                                                                  • 空間複雜 : ``
                                                                                                                                                                  • +
                                                                                                                                                                  +

                                                                                                                                                                  來源

                                                                                                                                                                  + +

                                                                                                                                                                  解答

                                                                                                                                                                  +

                                                                                                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0143.Reorder-List/main.go

                                                                                                                                                                  +
                                                                                                                                                                  package reorderlist
                                                                                                                                                                  +
                                                                                                                                                                  +/**
                                                                                                                                                                  + * Definition for singly-linked list.
                                                                                                                                                                  + * type ListNode struct {
                                                                                                                                                                  + *     Val int
                                                                                                                                                                  + *     Next *ListNode
                                                                                                                                                                  + * }
                                                                                                                                                                  + */
                                                                                                                                                                  +
                                                                                                                                                                  +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                                  +// 先用快慢指針找出Linked list的中間點
                                                                                                                                                                  +// 然後把Linked list分成兩半
                                                                                                                                                                  +// 再把後半的Linked list反轉
                                                                                                                                                                  +// 再把兩半的Linked list merge 起來
                                                                                                                                                                  +func reorderList(head *ListNode) {
                                                                                                                                                                  +    mid := middleNode(head)
                                                                                                                                                                  +
                                                                                                                                                                  +    // 2.反轉中間節點的下一個節點
                                                                                                                                                                  +    right := resverseNode(mid.Next)
                                                                                                                                                                  +    mid.Next = nil
                                                                                                                                                                  +    left := head
                                                                                                                                                                  +    mergeNode(left, right)
                                                                                                                                                                  +}
                                                                                                                                                                  +
                                                                                                                                                                  +// [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/)
                                                                                                                                                                  +func middleNode(head *ListNode) *ListNode {
                                                                                                                                                                  +    slow, fast := head, head
                                                                                                                                                                  +    for fast != nil && fast.Next != nil {
                                                                                                                                                                  +        slow = slow.Next
                                                                                                                                                                  +        fast = fast.Next.Next
                                                                                                                                                                  +    }
                                                                                                                                                                  +    return slow
                                                                                                                                                                  +}
                                                                                                                                                                  +
                                                                                                                                                                  +// [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/)
                                                                                                                                                                  +func resverseNode(head *ListNode) *ListNode {
                                                                                                                                                                  +    var pre *ListNode
                                                                                                                                                                  +    for head != nil {
                                                                                                                                                                  +        tmp := head.Next
                                                                                                                                                                  +        head.Next = pre
                                                                                                                                                                  +        pre = head
                                                                                                                                                                  +        head = tmp
                                                                                                                                                                  +    }
                                                                                                                                                                  +    return pre
                                                                                                                                                                  +}
                                                                                                                                                                  +
                                                                                                                                                                  +func mergeNode(l1, l2 *ListNode) {
                                                                                                                                                                  +    lcur, rcur := l1, l2
                                                                                                                                                                  +    for lcur != nil && rcur != nil {
                                                                                                                                                                  +        lcur.Next, rcur.Next, lcur, rcur = rcur, lcur.Next, lcur.Next, rcur.Next
                                                                                                                                                                  +    }
                                                                                                                                                                  +}
                                                                                                                                                                  +
                                                                                                                                                                  +

                                                                                                                                                                  Benchmark

                                                                                                                                                                  +
                                                                                                                                                                  
                                                                                                                                                                  +
                                                                                                                                                                  +
                                                                                                                                                                  +
                                                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                  + +
                                                                                                                                                                  + +
                                                                                                                                                                  +
                                                                                                                                                                  +
                                                                                                                                                                  + +

                                                                                                                                                                  results matching ""

                                                                                                                                                                  +
                                                                                                                                                                    + +
                                                                                                                                                                    +
                                                                                                                                                                    + +

                                                                                                                                                                    No results matching ""

                                                                                                                                                                    + +
                                                                                                                                                                    +
                                                                                                                                                                    +
                                                                                                                                                                    + +
                                                                                                                                                                    +
                                                                                                                                                                    + +
                                                                                                                                                                    + + + + + + +
                                                                                                                                                                    + + +
                                                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0143.Reorder-List/main.go b/Leetcode/0143.Reorder-List/main.go new file mode 100644 index 000000000..3415487a3 --- /dev/null +++ b/Leetcode/0143.Reorder-List/main.go @@ -0,0 +1,53 @@ +package reorderlist + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +// ๅ…ˆ็”จๅฟซๆ…ขๆŒ‡้‡ๆ‰พๅ‡บLinked list็š„ไธญ้–“้ปž +// ็„ถๅพŒๆŠŠLinked listๅˆ†ๆˆๅ…ฉๅŠ +// ๅ†ๆŠŠๅพŒๅŠ็š„Linked listๅ่ฝ‰ +// ๅ†ๆŠŠๅ…ฉๅŠ็š„Linked list merge ่ตทไพ† +func reorderList(head *ListNode) { + mid := middleNode(head) + + // 2.ๅ่ฝ‰ไธญ้–“็ฏ€้ปž็š„ไธ‹ไธ€ๅ€‹็ฏ€้ปž + right := resverseNode(mid.Next) + mid.Next = nil + left := head + mergeNode(left, right) +} + +// [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) +func middleNode(head *ListNode) *ListNode { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + } + return slow +} + +// [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) +func resverseNode(head *ListNode) *ListNode { + var pre *ListNode + for head != nil { + tmp := head.Next + head.Next = pre + pre = head + head = tmp + } + return pre +} + +func mergeNode(l1, l2 *ListNode) { + lcur, rcur := l1, l2 + for lcur != nil && rcur != nil { + lcur.Next, rcur.Next, lcur, rcur = rcur, lcur.Next, lcur.Next, rcur.Next + } +} diff --git a/Leetcode/0143.Reorder-List/main_test.go b/Leetcode/0143.Reorder-List/main_test.go new file mode 100644 index 000000000..0788b7309 --- /dev/null +++ b/Leetcode/0143.Reorder-List/main_test.go @@ -0,0 +1,34 @@ +package + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "bbbab", + 4, + }, +} + +func TestLongestPalindromeSubseq(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := LongestPalindromeSubseq(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubseq(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindromeSubseq(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/index.html b/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/index.html new file mode 100644 index 000000000..10fd6f3cc --- /dev/null +++ b/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/index.html @@ -0,0 +1,3883 @@ + + + + + + + 0167.Two Sum II Input Array Is Sorted ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                    +
                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                    + +
                                                                                                                                                                    + +
                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                    +
                                                                                                                                                                    + +
                                                                                                                                                                    +
                                                                                                                                                                    + +
                                                                                                                                                                    + +

                                                                                                                                                                    0167.Two Sum II Input Array Is Sorted

                                                                                                                                                                    題目

                                                                                                                                                                    +

                                                                                                                                                                    Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 < numbers.length.

                                                                                                                                                                    +

                                                                                                                                                                    Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2.

                                                                                                                                                                    +

                                                                                                                                                                    The tests are generated such that there is exactly one solution. You may not use the same element twice.

                                                                                                                                                                    +

                                                                                                                                                                    Your solution must use only constant extra space.

                                                                                                                                                                    +

                                                                                                                                                                    Example 1:

                                                                                                                                                                    +

                                                                                                                                                                    Input: numbers = [2,7,11,15], target = 9 +Output: [1,2] +Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. +Example 2:

                                                                                                                                                                    +

                                                                                                                                                                    Input: numbers = [2,3,4], target = 6 +Output: [1,3] +Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. +Example 3:

                                                                                                                                                                    +

                                                                                                                                                                    Input: numbers = [-1,0], target = -1 +Output: [1,2] +Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2].

                                                                                                                                                                    +

                                                                                                                                                                    Constraints:

                                                                                                                                                                    +

                                                                                                                                                                    2 <= numbers.length <= 3 * 104 +-1000 <= numbers[i] <= 1000 +numbers is sorted in non-decreasing order. +-1000 <= target <= 1000 +The tests are generated such that there is exactly one solution.

                                                                                                                                                                    +

                                                                                                                                                                    題目大意

                                                                                                                                                                    +

                                                                                                                                                                    找出兩個數之和等於 target 的兩個數位,要求輸出它們的下標。 注意一個數位不能使用 2 次。 下標從小到大輸出。 假定題目一定有一個解。

                                                                                                                                                                    +

                                                                                                                                                                    解題思路

                                                                                                                                                                    +

                                                                                                                                                                    Big O

                                                                                                                                                                    +
                                                                                                                                                                      +
                                                                                                                                                                    1. 使用1. Two Sun來解

                                                                                                                                                                      +
                                                                                                                                                                        +
                                                                                                                                                                      1. O(n^2) 的時間複雜度和 O(1)的空間複雜度暴力
                                                                                                                                                                      2. +
                                                                                                                                                                      3. 藉助哈希表使用 O(n) 的時間複雜度和 O(n) 的空間複雜度求解
                                                                                                                                                                      4. +
                                                                                                                                                                      +
                                                                                                                                                                    2. +
                                                                                                                                                                    3. 雙指針 +時間複雜度: O(n),其中 n 是陣列的長度。 兩個指標移動的總次數最多為 n 次。 +空間複雜度: O(1)

                                                                                                                                                                      +
                                                                                                                                                                    4. +
                                                                                                                                                                    +

                                                                                                                                                                    時間複雜 : 空間複雜 :

                                                                                                                                                                    +

                                                                                                                                                                    來源

                                                                                                                                                                    + +

                                                                                                                                                                    解答

                                                                                                                                                                    +

                                                                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main.go

                                                                                                                                                                    +
                                                                                                                                                                    package twosumiiinputarrayissorted
                                                                                                                                                                    +
                                                                                                                                                                    +// 雙指針. 時間複雜度: O(n),其中 n 是陣列的長度。 兩個指標移動的總次數最多為 n 次。
                                                                                                                                                                    +// 空間複雜度: O(1)
                                                                                                                                                                    +
                                                                                                                                                                    +func TwoSum(numbers []int, target int) []int {
                                                                                                                                                                    +    left, right := 0, len(numbers)-1
                                                                                                                                                                    +
                                                                                                                                                                    +    for left < right {
                                                                                                                                                                    +        if numbers[left]+numbers[right] == target {
                                                                                                                                                                    +            return []int{left + 1, right + 1}
                                                                                                                                                                    +        }
                                                                                                                                                                    +        if numbers[left]+numbers[right] < target {
                                                                                                                                                                    +            left++
                                                                                                                                                                    +        } else {
                                                                                                                                                                    +            right--
                                                                                                                                                                    +        }
                                                                                                                                                                    +    }
                                                                                                                                                                    +
                                                                                                                                                                    +    return nil
                                                                                                                                                                    +}
                                                                                                                                                                    +
                                                                                                                                                                    +// 使用 O(n^2) 的時間複雜度和 O(1)的空間複雜度暴力
                                                                                                                                                                    +// 或者藉助哈希表使用 O(n) 的時間複雜度和 O(n) 的空間複雜度求解
                                                                                                                                                                    +
                                                                                                                                                                    +func TwoSum2(numbers []int, target int) []int {
                                                                                                                                                                    +    m := make(map[int]int, len(numbers))
                                                                                                                                                                    +
                                                                                                                                                                    +    for i, v := range numbers {
                                                                                                                                                                    +        if j, ok := m[target-v]; ok {
                                                                                                                                                                    +            return []int{j + 1, i + 1}
                                                                                                                                                                    +        }
                                                                                                                                                                    +        m[v] = i
                                                                                                                                                                    +    }
                                                                                                                                                                    +    return nil
                                                                                                                                                                    +}
                                                                                                                                                                    +
                                                                                                                                                                    +

                                                                                                                                                                    Benchmark

                                                                                                                                                                    +
                                                                                                                                                                    go test -benchmem -run=none LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted -bench=.
                                                                                                                                                                    +goos: darwin
                                                                                                                                                                    +goarch: amd64
                                                                                                                                                                    +pkg: LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted
                                                                                                                                                                    +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
                                                                                                                                                                    +BenchmarkTwoSum-4       35161128                39.74 ns/op           16 B/op          1 allocs/op
                                                                                                                                                                    +BenchmarkTwoSum2-4      19309680                70.21 ns/op           16 B/op          1 allocs/op
                                                                                                                                                                    +PASS
                                                                                                                                                                    +ok      LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted   2.866s
                                                                                                                                                                    +
                                                                                                                                                                    +
                                                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                    + +
                                                                                                                                                                    + +
                                                                                                                                                                    +
                                                                                                                                                                    +
                                                                                                                                                                    + +

                                                                                                                                                                    results matching ""

                                                                                                                                                                    +
                                                                                                                                                                      + +
                                                                                                                                                                      +
                                                                                                                                                                      + +

                                                                                                                                                                      No results matching ""

                                                                                                                                                                      + +
                                                                                                                                                                      +
                                                                                                                                                                      +
                                                                                                                                                                      + +
                                                                                                                                                                      +
                                                                                                                                                                      + +
                                                                                                                                                                      + + + + + + +
                                                                                                                                                                      + + +
                                                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main.go b/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main.go new file mode 100644 index 000000000..e632906f1 --- /dev/null +++ b/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main.go @@ -0,0 +1,36 @@ +package twosumiiinputarrayissorted + +// ้›™ๆŒ‡้‡. ๆ™‚้–“่ค‡้›œๅบฆ๏ผš O(n)๏ผŒๅ…ถไธญ n ๆ˜ฏ้™ฃๅˆ—็š„้•ทๅบฆใ€‚ ๅ…ฉๅ€‹ๆŒ‡ๆจ™็งปๅ‹•็š„็ธฝๆฌกๆ•ธๆœ€ๅคš็‚บ n ๆฌกใ€‚ +// ็ฉบ้–“่ค‡้›œๅบฆ๏ผš O(1) + +func TwoSum(numbers []int, target int) []int { + left, right := 0, len(numbers)-1 + + for left < right { + if numbers[left]+numbers[right] == target { + return []int{left + 1, right + 1} + } + if numbers[left]+numbers[right] < target { + left++ + } else { + right-- + } + } + + return nil +} + +// ไฝฟ็”จ O(n^2) ็š„ๆ™‚้–“่ค‡้›œๅบฆๅ’Œ O(1)็š„็ฉบ้–“่ค‡้›œๅบฆๆšดๅŠ› +// ๆˆ–่€…่—‰ๅŠฉๅ“ˆๅธŒ่กจไฝฟ็”จ O(n) ็š„ๆ™‚้–“่ค‡้›œๅบฆๅ’Œ O(n) ็š„็ฉบ้–“่ค‡้›œๅบฆๆฑ‚่งฃ + +func TwoSum2(numbers []int, target int) []int { + m := make(map[int]int, len(numbers)) + + for i, v := range numbers { + if j, ok := m[target-v]; ok { + return []int{j + 1, i + 1} + } + m[v] = i + } + return nil +} diff --git a/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main_test.go b/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main_test.go new file mode 100644 index 000000000..9572ec1d5 --- /dev/null +++ b/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main_test.go @@ -0,0 +1,60 @@ +package twosumiiinputarrayissorted + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + arg2 int + want []int +}{ + { + []int{2, 7, 11, 15}, + 9, + []int{1, 2}, + }, +} + +func TestTwoSum(t *testing.T) { + for _, tt := range tests { + if got := TwoSum(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestTwoSum2(t *testing.T) { + for _, tt := range tests { + if got := TwoSum2(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkTwoSum(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + TwoSum(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkTwoSum2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + TwoSum2(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkTwoSum-4 35161128 39.74 ns/op 16 B/op 1 allocs/op +BenchmarkTwoSum2-4 19309680 70.21 ns/op 16 B/op 1 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted 2.866s +*/ diff --git a/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements.go b/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements.go new file mode 100644 index 000000000..1bcfb0185 --- /dev/null +++ b/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements.go @@ -0,0 +1,74 @@ +package removelinkedlistelements + +import ( + "LeetcodeGolang/structures" +) + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + +type ListNode = structures.ListNode + +// ๆ–นๆณ•ไธ€: ๅฆๅค–่€ƒๆ…ฎๅˆช้™คhead็ฏ€้ปž +func RemoveElements(head *ListNode, val int) *ListNode { + // ๅˆช้™คๅ€ผ็›ธๅŒ็š„head + for head != nil && head.Val == val { + head = head.Next + } + if head == nil { + return head + } + tmpHead := head + for tmpHead.Next != nil { + if tmpHead.Next.Val == val { + tmpHead.Next = tmpHead.Next.Next + } else { + tmpHead = tmpHead.Next + } + } + return head +} + +/* +ๆ–นๆณ•ไบŒ ๆทปๅŠ ่™›ๆ“ฌ็ฏ€้ปž, ๆ•ˆ่ƒฝ่ผƒๅฅฝ +ๅฏไปฅ่จญ็ฝฎไธ€ๅ€‹่™›ๆ“ฌ้ ญ็ต้ปžใ€๏ผŒ้€™ๆจฃๅŽŸ้Š้Œถ็š„ๆ‰€ๆœ‰็ฏ€้ปžๅฐฑ้ƒฝๅฏไปฅๆŒ‰็…ง็ตฑไธ€็š„ๆ–นๅผ้€ฒ่กŒ็งป้™คไบ† +return newHead.Next +*/ +func RemoveElementsVirtualNode(head *ListNode, val int) *ListNode { + if head == nil { + return head + } + // ๅปบ็ซ‹ไธ€ๅ€‹่™›ๆ“ฌ Head ็ฏ€้ปž + newHead := &ListNode{Val: 0, Next: head} + preHead := newHead + curHead := head + for curHead != nil { + if curHead.Val == val { + preHead.Next = curHead.Next + } else { + preHead = curHead + } + curHead = curHead.Next + } + return newHead.Next +} + +/* +ๆ–นๆณ•ไบŒ ้ž่ฟด +*/ +func RemoveElementsRecurse(head *ListNode, val int) *ListNode { + if head == nil { + return head + } + head.Next = RemoveElementsRecurse(head.Next, val) + if head.Val == val { + return head.Next + } else { + return head + } +} diff --git a/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements_test.go b/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements_test.go new file mode 100644 index 000000000..ec1245aa3 --- /dev/null +++ b/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements_test.go @@ -0,0 +1,100 @@ +package removelinkedlistelements + +import ( + "LeetcodeGolang/structures" + "reflect" + "testing" +) + +var tests = []struct { + arg1 *ListNode + arg2 int + want *ListNode +}{ + { + structures.Ints2List([]int{1, 2, 6, 3, 4, 5, 6}), + 6, + structures.Ints2List([]int{1, 2, 3, 4, 5}), + }, + { + structures.Ints2List([]int{7, 7, 7, 7, 7}), + 7, + structures.Ints2List([]int{}), + }, + { + structures.Ints2List([]int{1, 2, 3, 4, 5}), + 2, + structures.Ints2List([]int{1, 3, 4, 5}), + }, + { + structures.Ints2List([]int{1, 2, 3, 2, 3, 2, 3, 2}), + 2, + structures.Ints2List([]int{1, 3, 3, 3}), + }, + { + structures.Ints2List([]int{1, 2, 3, 4, 5}), + 10, + structures.Ints2List([]int{1, 2, 3, 4, 5}), + }, + { + structures.Ints2List([]int{1}), + 1, + structures.Ints2List([]int{}), + }, +} + +func TestRemoveElements(t *testing.T) { + for _, tt := range tests { + if got := RemoveElements(tt.arg1, tt.arg2); !reflect.DeepEqual(structures.List2Ints(got), structures.List2Ints(tt.want)) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + // got := RemoveElements(tt.arg1, tt.arg2) + // fmt.Println(structures.List2Ints(got)) + } +} + +func TestRemoveElementsRecurse(t *testing.T) { + for _, tt := range tests { + if got := RemoveElementsRecurse(tt.arg1, tt.arg2); !reflect.DeepEqual(structures.List2Ints(got), structures.List2Ints(tt.want)) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + // got := RemoveElements(tt.arg1, tt.arg2) + // fmt.Println(structures.List2Ints(got)) + } +} + +func TestRemoveElementsVirtualNode(t *testing.T) { + for _, tt := range tests { + if got := RemoveElementsVirtualNode(tt.arg1, tt.arg2); !reflect.DeepEqual(structures.List2Ints(got), structures.List2Ints(tt.want)) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkRemoveElements(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + RemoveElements(tests[i%6].arg1, tests[i%6].arg2) + } +} +func BenchmarkRemoveElementsVirtualNode(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + RemoveElementsVirtualNode(tests[i%6].arg1, tests[i%6].arg2) + } +} + +func BenchmarkRemoveElementsRecurse(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + RemoveElementsRecurse(tests[i%6].arg1, tests[i%6].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0203.Remove-Linked-List-Elements -bench=. +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkRemoveElements-8 195664567 5.953 ns/op 0 B/op 0 allocs/op +BenchmarkRemoveElementsVirtualNode-8 217690257 4.806 ns/op 0 B/op 0 allocs/op +BenchmarkRemoveElementsRecurse-8 79181312 14.31 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Leetcode/0203.Remove-Linked-List-Elements/index.html b/Leetcode/0203.Remove-Linked-List-Elements/index.html new file mode 100644 index 000000000..6def03991 --- /dev/null +++ b/Leetcode/0203.Remove-Linked-List-Elements/index.html @@ -0,0 +1,3881 @@ + + + + + + + 0203.Remove Linked List Elements ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                      +
                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                      + +
                                                                                                                                                                      + +
                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                      +
                                                                                                                                                                      + +
                                                                                                                                                                      +
                                                                                                                                                                      + +
                                                                                                                                                                      + +

                                                                                                                                                                      203. Remove Linked List Elements

                                                                                                                                                                      題目

                                                                                                                                                                      +

                                                                                                                                                                      Remove all elements from a linked list of integers that have value val.

                                                                                                                                                                      +

                                                                                                                                                                      Example :

                                                                                                                                                                      +
                                                                                                                                                                      Input: 1->2->6->3->4->5->6, val = 6
                                                                                                                                                                      +Output: 1->2->3->4->5
                                                                                                                                                                      +
                                                                                                                                                                      +

                                                                                                                                                                      題目大意

                                                                                                                                                                      +

                                                                                                                                                                      刪除鍊錶中所有指定值的結點。

                                                                                                                                                                      +

                                                                                                                                                                      解題思路

                                                                                                                                                                      +

                                                                                                                                                                      按照題意做即可

                                                                                                                                                                      +

                                                                                                                                                                      來源

                                                                                                                                                                      + +

                                                                                                                                                                      解答

                                                                                                                                                                      +

                                                                                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements.go

                                                                                                                                                                      +
                                                                                                                                                                      package removelinkedlistelements
                                                                                                                                                                      +
                                                                                                                                                                      +import (
                                                                                                                                                                      +    "LeetcodeGolang/structures"
                                                                                                                                                                      +)
                                                                                                                                                                      +
                                                                                                                                                                      +/**
                                                                                                                                                                      + * Definition for singly-linked list.
                                                                                                                                                                      + * type ListNode struct {
                                                                                                                                                                      + *     Val int
                                                                                                                                                                      + *     Next *ListNode
                                                                                                                                                                      + * }
                                                                                                                                                                      + */
                                                                                                                                                                      +
                                                                                                                                                                      +type ListNode = structures.ListNode
                                                                                                                                                                      +
                                                                                                                                                                      +// 方法一: 另外考慮刪除head節點
                                                                                                                                                                      +func RemoveElements(head *ListNode, val int) *ListNode {
                                                                                                                                                                      +    // 刪除值相同的head
                                                                                                                                                                      +    for head != nil && head.Val == val {
                                                                                                                                                                      +        head = head.Next
                                                                                                                                                                      +    }
                                                                                                                                                                      +    if head == nil {
                                                                                                                                                                      +        return head
                                                                                                                                                                      +    }
                                                                                                                                                                      +    tmpHead := head
                                                                                                                                                                      +    for tmpHead.Next != nil {
                                                                                                                                                                      +        if tmpHead.Next.Val == val {
                                                                                                                                                                      +            tmpHead.Next = tmpHead.Next.Next
                                                                                                                                                                      +        } else {
                                                                                                                                                                      +            tmpHead = tmpHead.Next
                                                                                                                                                                      +        }
                                                                                                                                                                      +    }
                                                                                                                                                                      +    return head
                                                                                                                                                                      +}
                                                                                                                                                                      +
                                                                                                                                                                      +/*
                                                                                                                                                                      +方法二 添加虛擬節點, 效能較好
                                                                                                                                                                      +可以設置一個虛擬頭結點」,這樣原鍊錶的所有節點就都可以按照統一的方式進行移除了
                                                                                                                                                                      +return newHead.Next
                                                                                                                                                                      +*/
                                                                                                                                                                      +func RemoveElementsVirtualNode(head *ListNode, val int) *ListNode {
                                                                                                                                                                      +    if head == nil {
                                                                                                                                                                      +        return head
                                                                                                                                                                      +    }
                                                                                                                                                                      +    // 建立一個虛擬 Head 節點
                                                                                                                                                                      +    newHead := &ListNode{Val: 0, Next: head}
                                                                                                                                                                      +    preHead := newHead
                                                                                                                                                                      +    curHead := head
                                                                                                                                                                      +    for curHead != nil {
                                                                                                                                                                      +        if curHead.Val == val {
                                                                                                                                                                      +            preHead.Next = curHead.Next
                                                                                                                                                                      +        } else {
                                                                                                                                                                      +            preHead = curHead
                                                                                                                                                                      +        }
                                                                                                                                                                      +        curHead = curHead.Next
                                                                                                                                                                      +    }
                                                                                                                                                                      +    return newHead.Next
                                                                                                                                                                      +}
                                                                                                                                                                      +
                                                                                                                                                                      +/*
                                                                                                                                                                      +方法二 遞迴
                                                                                                                                                                      +*/
                                                                                                                                                                      +func RemoveElementsRecurse(head *ListNode, val int) *ListNode {
                                                                                                                                                                      +    if head == nil {
                                                                                                                                                                      +        return head
                                                                                                                                                                      +    }
                                                                                                                                                                      +    head.Next = RemoveElementsRecurse(head.Next, val)
                                                                                                                                                                      +    if head.Val == val {
                                                                                                                                                                      +        return head.Next
                                                                                                                                                                      +    } else {
                                                                                                                                                                      +        return head
                                                                                                                                                                      +    }
                                                                                                                                                                      +}
                                                                                                                                                                      +
                                                                                                                                                                      +
                                                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                      + +
                                                                                                                                                                      + +
                                                                                                                                                                      +
                                                                                                                                                                      +
                                                                                                                                                                      + +

                                                                                                                                                                      results matching ""

                                                                                                                                                                      +
                                                                                                                                                                        + +
                                                                                                                                                                        +
                                                                                                                                                                        + +

                                                                                                                                                                        No results matching ""

                                                                                                                                                                        + +
                                                                                                                                                                        +
                                                                                                                                                                        +
                                                                                                                                                                        + +
                                                                                                                                                                        +
                                                                                                                                                                        + +
                                                                                                                                                                        + + + + + + +
                                                                                                                                                                        + + +
                                                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0206.Reverse-Linked-List/index.html b/Leetcode/0206.Reverse-Linked-List/index.html new file mode 100644 index 000000000..89f709547 --- /dev/null +++ b/Leetcode/0206.Reverse-Linked-List/index.html @@ -0,0 +1,3870 @@ + + + + + + + 206. Reverse Linked List ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                        +
                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                        + +
                                                                                                                                                                        + +
                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                        +
                                                                                                                                                                        + +
                                                                                                                                                                        +
                                                                                                                                                                        + +
                                                                                                                                                                        + +

                                                                                                                                                                        206. Reverse Linked List

                                                                                                                                                                        題目

                                                                                                                                                                        +

                                                                                                                                                                        Given the head of a singly linked list, reverse the list, and return the reversed list.

                                                                                                                                                                        +

                                                                                                                                                                        Example 1: +

                                                                                                                                                                        +
                                                                                                                                                                        Input: head = [1,2,3,4,5]
                                                                                                                                                                        +Output: [5,4,3,2,1]
                                                                                                                                                                        +

                                                                                                                                                                        Example 2: +

                                                                                                                                                                        +
                                                                                                                                                                        Input: head = [1,2]
                                                                                                                                                                        +Output: [2,1]
                                                                                                                                                                        +

                                                                                                                                                                        Example 3:

                                                                                                                                                                        +
                                                                                                                                                                        Input: head = []
                                                                                                                                                                        +Output: []
                                                                                                                                                                        +

                                                                                                                                                                        Constraints:

                                                                                                                                                                        +
                                                                                                                                                                          +
                                                                                                                                                                        • The number of nodes in the list is the range [0, 5000].
                                                                                                                                                                        • +
                                                                                                                                                                        • -5000 <= Node.val <= 5000
                                                                                                                                                                        • +
                                                                                                                                                                        +

                                                                                                                                                                        Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

                                                                                                                                                                        +

                                                                                                                                                                        題目大意

                                                                                                                                                                        +

                                                                                                                                                                        將 Linked List 反向

                                                                                                                                                                        +

                                                                                                                                                                        解題思路

                                                                                                                                                                        +

                                                                                                                                                                        來源

                                                                                                                                                                        + +

                                                                                                                                                                        解答

                                                                                                                                                                        +

                                                                                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0000.kkkk/main.go

                                                                                                                                                                        +
                                                                                                                                                                        package reverselinkedlist
                                                                                                                                                                        +
                                                                                                                                                                        +import (
                                                                                                                                                                        +    . "LeetcodeGolang/structures"
                                                                                                                                                                        +)
                                                                                                                                                                        +
                                                                                                                                                                        +/**
                                                                                                                                                                        + * Definition for singly-linked list.
                                                                                                                                                                        + * type ListNode struct {
                                                                                                                                                                        + *     Val int
                                                                                                                                                                        + *     Next *ListNode
                                                                                                                                                                        + * }
                                                                                                                                                                        + */
                                                                                                                                                                        +
                                                                                                                                                                        +func ReverseList(head *ListNode) *ListNode {
                                                                                                                                                                        +    if head == nil || head.Next == nil {
                                                                                                                                                                        +        return head
                                                                                                                                                                        +    }
                                                                                                                                                                        +
                                                                                                                                                                        +    var prev *ListNode
                                                                                                                                                                        +
                                                                                                                                                                        +    for head != nil {
                                                                                                                                                                        +        next := head.Next
                                                                                                                                                                        +        head.Next = prev
                                                                                                                                                                        +        prev = head
                                                                                                                                                                        +        head = next
                                                                                                                                                                        +    }
                                                                                                                                                                        +
                                                                                                                                                                        +    return prev
                                                                                                                                                                        +}
                                                                                                                                                                        +
                                                                                                                                                                        +func ReverseListRecursively(head *ListNode) *ListNode {
                                                                                                                                                                        +    return ListRecursivelyChild(head, nil)
                                                                                                                                                                        +}
                                                                                                                                                                        +
                                                                                                                                                                        +func ListRecursivelyChild(current *ListNode, prev *ListNode) *ListNode {
                                                                                                                                                                        +    if current == nil {
                                                                                                                                                                        +        return prev
                                                                                                                                                                        +    }
                                                                                                                                                                        +    next := current.Next
                                                                                                                                                                        +    current.Next = prev
                                                                                                                                                                        +    return ListRecursivelyChild(next, current)
                                                                                                                                                                        +}
                                                                                                                                                                        +
                                                                                                                                                                        +

                                                                                                                                                                        Benchmark

                                                                                                                                                                        +
                                                                                                                                                                        goos: darwin
                                                                                                                                                                        +goarch: amd64
                                                                                                                                                                        +pkg: LeetcodeGolang/Leetcode/0206.Reverse-Linked-List
                                                                                                                                                                        +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                        +BenchmarkReverseList-8                  1000000000               0.7960 ns/op          0 B/op          0 allocs/op
                                                                                                                                                                        +BenchmarkReverseListRecursively-8       276534334                4.374 ns/op           0 B/op          0 allocs/op
                                                                                                                                                                        +PASS
                                                                                                                                                                        +ok      LeetcodeGolang/Leetcode/0206.Reverse-Linked-List        2.597s
                                                                                                                                                                        +
                                                                                                                                                                        +
                                                                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                        + +
                                                                                                                                                                        + +
                                                                                                                                                                        +
                                                                                                                                                                        +
                                                                                                                                                                        + +

                                                                                                                                                                        results matching ""

                                                                                                                                                                        +
                                                                                                                                                                          + +
                                                                                                                                                                          +
                                                                                                                                                                          + +

                                                                                                                                                                          No results matching ""

                                                                                                                                                                          + +
                                                                                                                                                                          +
                                                                                                                                                                          +
                                                                                                                                                                          + +
                                                                                                                                                                          +
                                                                                                                                                                          + +
                                                                                                                                                                          + + + + + + +
                                                                                                                                                                          + + +
                                                                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0206.Reverse-Linked-List/main.go b/Leetcode/0206.Reverse-Linked-List/main.go new file mode 100644 index 000000000..6b5d6cc0a --- /dev/null +++ b/Leetcode/0206.Reverse-Linked-List/main.go @@ -0,0 +1,43 @@ +package reverselinkedlist + +import ( + . "LeetcodeGolang/structures" +) + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + +func ReverseList(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + var prev *ListNode + + for head != nil { + next := head.Next + head.Next = prev + prev = head + head = next + } + + return prev +} + +func ReverseListRecursively(head *ListNode) *ListNode { + return ListRecursivelyChild(head, nil) +} + +func ListRecursivelyChild(current *ListNode, prev *ListNode) *ListNode { + if current == nil { + return prev + } + next := current.Next + current.Next = prev + return ListRecursivelyChild(next, current) +} diff --git a/Leetcode/0206.Reverse-Linked-List/main_test.go b/Leetcode/0206.Reverse-Linked-List/main_test.go new file mode 100644 index 000000000..7aad327ba --- /dev/null +++ b/Leetcode/0206.Reverse-Linked-List/main_test.go @@ -0,0 +1,67 @@ +package reverselinkedlist + +import ( + . "LeetcodeGolang/structures" + "reflect" + "testing" +) + +var tests = []struct { + arg1 *ListNode + want *ListNode +}{ + { + Ints2List([]int{1, 2, 3, 4, 5}), + Ints2List([]int{5, 4, 3, 2, 1}), + }, + { + Ints2List([]int{1, 2}), + Ints2List([]int{2, 1}), + }, + { + Ints2List([]int{}), + Ints2List([]int{}), + }, +} + +func TestReverseList(t *testing.T) { + for _, tt := range tests { + if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestReverseListRecursively(t *testing.T) { + for _, tt := range tests { + if got := ReverseListRecursively(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkReverseList(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ReverseList(tests[0].arg1) + } +} + +func BenchmarkReverseListRecursively(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ReverseListRecursively(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0206.Reverse-Linked-List -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0206.Reverse-Linked-List +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkReverseList-8 1000000000 0.7960 ns/op 0 B/op 0 allocs/op +BenchmarkReverseListRecursively-8 276534334 4.374 ns/op 0 B/op 0 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0206.Reverse-Linked-List 2.597s +*/ diff --git a/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum.go b/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum.go new file mode 100644 index 000000000..c86947a29 --- /dev/null +++ b/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum.go @@ -0,0 +1,119 @@ +package minimumsizesubarraysum + +import ( + "math" + "sort" +) + +// MinSubArrayLenBurst : ๆšดๅŠ›่งฃ ๆ™‚้–“่ค‡้›œ O(n^2), ็ฉบ้–“่ค‡้›œ O(1) +func MinSubArrayLenBurst(target int, nums []int) int { + lens := len(nums) + if lens <= 0 { + return 0 + } + + minSize := math.MaxInt32 + for i := 0; i < lens; i++ { + sum := 0 + for j := i; j < lens; j++ { + sum += nums[j] + if sum >= target { + minSize = min(minSize, j-i+1) + } + } + } + if minSize == math.MaxInt32 { + minSize = 0 + } + return minSize +} + +// MinSubArrayLenSlidingWindow : ๆป‘ๅ‹•่ฆ–็ช— ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +// ๆป‘ๅ‹•็ช—ๅฃ็š„็ฒพๅฆ™ไน‹่™•ๅœจๆ–ผๆ นๆ“š็•ถๅ‰ๅญๅบๅˆ—ๅ’Œๅคงๅฐ็š„ๆƒ…ๆณ๏ผŒไธๆ–ท่ชฟ็ฏ€ๅญๅบๅˆ—็š„่ตทๅง‹ไฝ็ฝฎใ€‚ๅพž่€Œๅฐ‡O(n^2)็š„ๆšดๅŠ›่งฃๆณ•้™็‚บO(n) +func MinSubArrayLenSlidingWindow(target int, nums []int) int { + lens := len(nums) + if lens <= 0 { + return 0 + } + minSize := math.MaxInt32 + + start, end, sum := 0, 0, 0 + for end < lens { + sum += nums[end] + for sum >= target { + minSize = min(minSize, end-start+1) + sum -= nums[start] + start++ + } + end++ + + } + + if minSize == math.MaxInt32 { + minSize = 0 + } + return minSize +} + +/* +MinSubArrayLenBinarysearch : ๅ‰็ผ€ๅ’Œ + ไบŒๅˆ†ๆŸฅๆ‰พ O(nlog(n)) +็‚บไบ†ไฝฟ็”จไบŒๅˆ†ๆŸฅๆ‰พ๏ผŒ้œ€่ฆ้กๅค–ๅ‰ตๅปบไธ€ๅ€‹ๆ•ธ็ต„ sums ็”จๆ–ผๅญ˜ๅ„ฒๆ•ธ็ต„nums ็š„ๅ‰็ถดๅ’Œ๏ผŒๅ…ถไธญ sums[i] ่กจ็คบๅพž nums[0] ๅˆฐ nums[iโˆ’1] ็š„ๅ…ƒ็ด ๅ’Œใ€‚ +ๅพ—ๅˆฐๅ‰็ถดๅ’Œไน‹ๅพŒ๏ผŒๅฐๆ–ผๆฏๅ€‹้–‹ๅง‹ไธ‹ๆจ™i๏ผŒๅฏ้€š้ŽไบŒๅˆ†ๆŸฅๆ‰พๅพ—ๅˆฐๅคงๆ–ผๆˆ–็ญ‰ๆ–ผ i ็š„ๆœ€ๅฐไธ‹ๆจ™ bound๏ผŒ +ไฝฟๅพ— sums[bound]-sums[i-1] >= s๏ผŒ +ไธฆๆ›ดๆ–ฐๅญๆ•ธ็ต„็š„ๆœ€ๅฐ้•ทๅบฆ๏ผˆๆญคๆ™‚ๅญๆ•ธ็ต„็š„้•ทๅบฆๆ˜ฏ bound -(i-1) )ใ€‚ +C++ ็š„ lower_bound๏ผŒJava ็š„ Arrays.binarySearch + +ๅ› ็‚บ้€™้“้กŒไฟ่ญ‰ไบ†ๆ•ธ็ต„ไธญๆฏๅ€‹ๅ…ƒ็ด ้ƒฝ็‚บๆญฃ๏ผŒๆ‰€ไปฅๅ‰็ถดๅ’Œไธ€ๅฎšๆ˜ฏ้žๅขž็š„๏ผŒ้€™ไธ€้ปžไฟ่ญ‰ไบ†ไบŒๅˆ†็š„ๆญฃ็ขบๆ€งใ€‚ๅฆ‚ๆžœ้กŒ็›ฎๆฒ’ๆœ‰่ชชๆ˜Žๆ•ธ็ต„ไธญๆฏๅ€‹ๅ…ƒ็ด ้ƒฝ็‚บๆญฃ๏ผŒ้€™่ฃกๅฐฑไธ่ƒฝไฝฟ็”จไบŒๅˆ†ไพ†ๆŸฅๆ‰พ้€™ๅ€‹ไฝ็ฝฎไบ†ใ€‚ +*/ +func MinSubArrayLenBinarysearch(target int, nums []int) int { + lens := len(nums) + if lens <= 0 { + return 0 + } + minSize := math.MaxInt32 + + // sums[i] ่กจ็คบๅพž nums[0] ๅˆฐ nums[iโˆ’1] + sums := make([]int, lens+1) + // ็‚บไบ†ๆ–นไพฟ่จˆ็ฎ— size = lens + 1 + // sums[0] = 0, ๅ‰0ๅ€‹็š„ๅ…ƒ็ด ๅ’Œ + // sums[1] = nums[0] , ๅ‰1ๅ€‹ๅ…ƒ็ด ๅ’Œ็‚บ nums[0] + for i := 1; i <= lens; i++ { + sums[i] = sums[i-1] + nums[i-1] + } + // fmt.Println("sums", sums) + for i := 1; i <= lens; i++ { + /* + target 7 + input 2 3 1 2 4 3 + ----------------------------------- + i 0 1 2 3 4 5 6 + ----------------------------------- + sums 0 2 5 6 8 12 15 // input ็š„ๅ‰ n ๅ€‹ๅ…ƒ็ด ๅ’Œ + tmpTarge 7 9 12 13 15 19 // tmpTarge = target + sums[i-1] + bound 4 5 5 6 6 7 // bound = sort.SearchInts(sums, tmpTarge) + bound-(i-1) 4 4 3 3 2 2 + minSize 4 4 3 3 2 2 + */ + tmpTarge := target + sums[i-1] + bound := sort.SearchInts(sums, tmpTarge) + // if bound < 0 { + // bound = -bound - 1 + // } + if bound <= lens { + minSize = min(minSize, bound-(i-1)) + } + // fmt.Println("i:", i, " tmpTarge", tmpTarge, " bound:", bound, " bound-(i-1)", bound-(i-1), " minSize:", minSize) + } + + if minSize == math.MaxInt32 { + minSize = 0 + } + return minSize +} + +func min(x, y int) int { + if x < y { + return x + } + return y +} diff --git a/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum_test.go b/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum_test.go new file mode 100644 index 000000000..543f4c830 --- /dev/null +++ b/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum_test.go @@ -0,0 +1,77 @@ +package minimumsizesubarraysum + +import ( + "testing" +) + +var tests = []struct { + arg1 int + arg2 []int + want int +}{ + { + 7, + []int{2, 3, 1, 2, 4, 3}, + 2, + }, + // { + // 4, + // []int{1, 4, 4}, + // 1, + // }, + // { + // 11, + // []int{1, 1, 1, 1, 1, 1, 1, 1}, + // 0, + // }, +} + +func TestMinSubArrayLenBurst(t *testing.T) { + for _, tt := range tests { + if got := MinSubArrayLenBurst(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestMinSubArrayLenSlidingWindow(t *testing.T) { + for _, tt := range tests { + if got := MinSubArrayLenSlidingWindow(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestMinSubArrayLenBinarysearch(t *testing.T) { + for _, tt := range tests { + if got := MinSubArrayLenBinarysearch(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func BenchmarkMinSubArrayLenBurst(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinSubArrayLenBurst(tests[0].arg1, tests[0].arg2) + } +} +func BenchmarkMinSubArrayLenSlidingWindow(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinSubArrayLenSlidingWindow(tests[0].arg1, tests[0].arg2) + } +} +func BenchmarkMinSubArrayLenBinarysearch(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinSubArrayLenBinarysearch(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0209.Minimum-Size-Subarray-Sum -bench=. +BenchmarkMinSubArrayLenBurst-4 27345652 41.67 ns/op 0 B/op 0 allocs/op +BenchmarkMinSubArrayLenSlidingWindow-4 87522610 13.67 ns/op 0 B/op 0 allocs/op +BenchmarkMinSubArrayLenBinarysearch-4 8496684 136.7 ns/op 64 B/op 1 allocs/op +*/ diff --git a/Leetcode/0209.Minimum-Size-Subarray-Sum/index.html b/Leetcode/0209.Minimum-Size-Subarray-Sum/index.html new file mode 100644 index 000000000..65119a164 --- /dev/null +++ b/Leetcode/0209.Minimum-Size-Subarray-Sum/index.html @@ -0,0 +1,3868 @@ + + + + + + + 0209. Minimum Size Subarray Sum ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                          +
                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                          + +
                                                                                                                                                                          + +
                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                          +
                                                                                                                                                                          + +
                                                                                                                                                                          +
                                                                                                                                                                          + +
                                                                                                                                                                          + +

                                                                                                                                                                          209. Minimum Size Subarray Sum

                                                                                                                                                                          题目

                                                                                                                                                                          +

                                                                                                                                                                          Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.

                                                                                                                                                                          +

                                                                                                                                                                          Example 1:

                                                                                                                                                                          +
                                                                                                                                                                          Input: s = 7, nums = [2,3,1,2,4,3]
                                                                                                                                                                          +Output: 2
                                                                                                                                                                          +Explanation: the subarray [4,3] has the minimal length under the problem constraint.
                                                                                                                                                                          +
                                                                                                                                                                          +
                                                                                                                                                                          Input: s = 4, nums = [1,4,4]
                                                                                                                                                                          +Output: 1
                                                                                                                                                                          +
                                                                                                                                                                          Input: s = 11, nums = [1,1,1,1,1,1,1,1]
                                                                                                                                                                          +Output: 0
                                                                                                                                                                          +

                                                                                                                                                                          Follow up:

                                                                                                                                                                          +

                                                                                                                                                                          If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).

                                                                                                                                                                          +

                                                                                                                                                                          題目大意

                                                                                                                                                                          +

                                                                                                                                                                          給定一個整型數組和一個數字 s,找到數組中最短的一個連續子數組,使得連續子數組的數字之和 sum>=s,返回最短的連續子數組的返回值。

                                                                                                                                                                          +

                                                                                                                                                                          解題思路

                                                                                                                                                                          +

                                                                                                                                                                          這一題的解題思路是用滑動窗口。在滑動窗口[i,j]之間不斷往後移動,如果總和小於s,就擴大右邊界j,不斷加入右邊的值,直到sum > s,之和再縮小i 的左邊界,不斷縮小直到sum < s,這時候右邊界又可以往右移動。以此類推。

                                                                                                                                                                          +

                                                                                                                                                                          進階

                                                                                                                                                                          +

                                                                                                                                                                          如果你已經實現 O(n) 時間複雜度的解法, 請嘗試設計一個 O(n log(n)) 時間複雜度的解法。

                                                                                                                                                                          +

                                                                                                                                                                          來源

                                                                                                                                                                          + +

                                                                                                                                                                          解答

                                                                                                                                                                          +

                                                                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum.go

                                                                                                                                                                          +
                                                                                                                                                                          package minimumsizesubarraysum
                                                                                                                                                                          +
                                                                                                                                                                          +import (
                                                                                                                                                                          +    "math"
                                                                                                                                                                          +    "sort"
                                                                                                                                                                          +)
                                                                                                                                                                          +
                                                                                                                                                                          +// MinSubArrayLenBurst : 暴力解 時間複雜 O(n^2), 空間複雜 O(1)
                                                                                                                                                                          +func MinSubArrayLenBurst(target int, nums []int) int {
                                                                                                                                                                          +    lens := len(nums)
                                                                                                                                                                          +    if lens <= 0="" {="" return="" }="" minsize="" :="math.MaxInt32" for="" i="" <="" lens;="" i++="" sum="" j="" j++="" +="nums[j]" if="">= target {
                                                                                                                                                                          +                minSize = min(minSize, j-i+1)
                                                                                                                                                                          +            }
                                                                                                                                                                          +        }
                                                                                                                                                                          +    }
                                                                                                                                                                          +    if minSize == math.MaxInt32 {
                                                                                                                                                                          +        minSize = 0
                                                                                                                                                                          +    }
                                                                                                                                                                          +    return minSize
                                                                                                                                                                          +}
                                                                                                                                                                          +
                                                                                                                                                                          +// MinSubArrayLenSlidingWindow : 滑動視窗 時間複雜 O(n), 空間複雜 O(1)
                                                                                                                                                                          +// 滑動窗口的精妙之處在於根據當前子序列和大小的情況,不斷調節子序列的起始位置。從而將O(n^2)的暴力解法降為O(n)
                                                                                                                                                                          +func MinSubArrayLenSlidingWindow(target int, nums []int) int {
                                                                                                                                                                          +    lens := len(nums)
                                                                                                                                                                          +    if lens <= 0="" {="" return="" }="" minsize="" :="math.MaxInt32" start,="" end,="" sum="" 0,="" for="" end="" <="" lens="" +="nums[end]">= target {
                                                                                                                                                                          +            minSize = min(minSize, end-start+1)
                                                                                                                                                                          +            sum -= nums[start]
                                                                                                                                                                          +            start++
                                                                                                                                                                          +        }
                                                                                                                                                                          +        end++
                                                                                                                                                                          +
                                                                                                                                                                          +    }
                                                                                                                                                                          +
                                                                                                                                                                          +    if minSize == math.MaxInt32 {
                                                                                                                                                                          +        minSize = 0
                                                                                                                                                                          +    }
                                                                                                                                                                          +    return minSize
                                                                                                                                                                          +}
                                                                                                                                                                          +
                                                                                                                                                                          +/*
                                                                                                                                                                          +MinSubArrayLenBinarysearch : 前缀和 + 二分查找  O(nlog(n))
                                                                                                                                                                          +為了使用二分查找,需要額外創建一個數組 sums 用於存儲數組nums 的前綴和,其中 sums[i] 表示從 nums[0] 到 nums[i−1] 的元素和。
                                                                                                                                                                          +得到前綴和之後,對於每個開始下標i,可通過二分查找得到大於或等於 i 的最小下標 bound,
                                                                                                                                                                          +使得 sums[bound]-sums[i-1] >= s,
                                                                                                                                                                          +並更新子數組的最小長度(此時子數組的長度是 bound -(i-1) )。
                                                                                                                                                                          +C++ 的 lower_bound,Java 的 Arrays.binarySearch
                                                                                                                                                                          +
                                                                                                                                                                          +因為這道題保證了數組中每個元素都為正,所以前綴和一定是遞增的,這一點保證了二分的正確性。如果題目沒有說明數組中每個元素都為正,這裡就不能使用二分來查找這個位置了。
                                                                                                                                                                          +*/
                                                                                                                                                                          +func MinSubArrayLenBinarysearch(target int, nums []int) int {
                                                                                                                                                                          +    lens := len(nums)
                                                                                                                                                                          +    if lens 
                                                                                                                                                                          +
                                                                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                          + +
                                                                                                                                                                          + +
                                                                                                                                                                          +
                                                                                                                                                                          +
                                                                                                                                                                          + +

                                                                                                                                                                          results matching ""

                                                                                                                                                                          +
                                                                                                                                                                            + +
                                                                                                                                                                            +
                                                                                                                                                                            + +

                                                                                                                                                                            No results matching ""

                                                                                                                                                                            + +
                                                                                                                                                                            +
                                                                                                                                                                            +
                                                                                                                                                                            + +
                                                                                                                                                                            +
                                                                                                                                                                            + +
                                                                                                                                                                            + + + + + + +
                                                                                                                                                                            + + +
                                                                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0215.Kth-Largest-Element-in-an-Array/index.html b/Leetcode/0215.Kth-Largest-Element-in-an-Array/index.html new file mode 100644 index 000000000..27c26f35b --- /dev/null +++ b/Leetcode/0215.Kth-Largest-Element-in-an-Array/index.html @@ -0,0 +1,3906 @@ + + + + + + + 0215. Kth Largest Element in an Array ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                            +
                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                            + +
                                                                                                                                                                            + +
                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                            +
                                                                                                                                                                            + +
                                                                                                                                                                            +
                                                                                                                                                                            + +
                                                                                                                                                                            + +

                                                                                                                                                                            0215. Kth Largest Element in an Array

                                                                                                                                                                            題目

                                                                                                                                                                            +

                                                                                                                                                                            Given an integer array nums and an integer k, return the kth largest element in the array.

                                                                                                                                                                            +

                                                                                                                                                                            Note that it is the kth largest element in the sorted order, not the kth distinct element.

                                                                                                                                                                            +

                                                                                                                                                                            Can you solve it without sorting?

                                                                                                                                                                            +

                                                                                                                                                                            Example 1:

                                                                                                                                                                            +
                                                                                                                                                                            Input: nums = [3,2,1,5,6,4], k = 2
                                                                                                                                                                            +Output: 5
                                                                                                                                                                            +

                                                                                                                                                                            Example 2:

                                                                                                                                                                            +
                                                                                                                                                                            Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
                                                                                                                                                                            +Output: 4
                                                                                                                                                                            +

                                                                                                                                                                            Constraints:

                                                                                                                                                                            +
                                                                                                                                                                              +
                                                                                                                                                                            • 1 <= k <= nums.length <= 105
                                                                                                                                                                            • +
                                                                                                                                                                            • -104 <= nums[i] <= 104
                                                                                                                                                                            • +
                                                                                                                                                                            +

                                                                                                                                                                            題目大意

                                                                                                                                                                            +
                                                                                                                                                                              +
                                                                                                                                                                            1. 數組中的第K個最大元素 (Kth Largest Element in an Array)
                                                                                                                                                                            2. +
                                                                                                                                                                            +

                                                                                                                                                                            給定一個未排序的整數數組,找到其中第K個最大的元素。

                                                                                                                                                                            +

                                                                                                                                                                            解題思路

                                                                                                                                                                            +

                                                                                                                                                                            一種常見的解法是使用堆數據結構。我們可以維護一個大小為K的最小堆,初始時將數組的前K個元素加入堆中。然後遍歷數組的剩餘元素,如果當前元素比堆頂元素大,則將堆頂元素出堆,並將當前元素加入堆中。最後堆頂元素即為第K個最大的元素。

                                                                                                                                                                            +
                                                                                                                                                                              +
                                                                                                                                                                            • 時間複雜度: 構建堆的時間複雜度為O(K),遍歷數組的時間複雜度為O((N-K)logK),因此總的時間複雜度為O(NlogK)。
                                                                                                                                                                            • +
                                                                                                                                                                            • 空間複雜度: 使用了大小為K的最小堆來存儲元素,因此空間複雜度為O(K)。
                                                                                                                                                                            • +
                                                                                                                                                                            +

                                                                                                                                                                            在快速選擇 quickselect 的 partition 操作中,每次 partition 操作結束都會返回一個點,這個標定點的下標和最終排序之後有序數組中這個元素所在的下標是一致的。利用這個特性,我們可以不斷的劃分數組區間,最終找到第 K 大的元素。執行一次 partition 操作以後,如果這個元素的下標比 K 小,那麼接著就在後邊的區間繼續執行 partition 操作;如果這個元素的下標比 K 大,那麼就在左邊的區間繼續執行 partition 操作;如果相等就直接輸出這個下標對應的數組元素即可。 +快速選擇 quickselect 的思路實現的算法時間複雜度為 O(n),空間複雜度為 O(logn)

                                                                                                                                                                            +

                                                                                                                                                                            來源

                                                                                                                                                                            + +

                                                                                                                                                                            解答

                                                                                                                                                                            +

                                                                                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0215.Kth-Largest-Element-in-an-Array/main.go

                                                                                                                                                                            +
                                                                                                                                                                            package kthlargestelementinanarray
                                                                                                                                                                            +
                                                                                                                                                                            +import (
                                                                                                                                                                            +    "container/heap"
                                                                                                                                                                            +    "sort"
                                                                                                                                                                            +)
                                                                                                                                                                            +
                                                                                                                                                                            +// 解法一:用Heap資料結構
                                                                                                                                                                            +// container/heap包可以用来構造優先級Queue。
                                                                                                                                                                            +// Heap(堆積)其實是一個Complete Binary Tree(完全二元樹).
                                                                                                                                                                            +// Go的Heap特性是 各個節點都自己是其子樹的根, 且值是最小的(index = 0 的值是最小的).
                                                                                                                                                                            +// 同個根節點的左子樹的值會小於右子樹
                                                                                                                                                                            +func FindKthLargestHeap(nums []int, k int) int {
                                                                                                                                                                            +    if k <= 0="" ||="" k=""> len(nums) {
                                                                                                                                                                            +        return 0
                                                                                                                                                                            +    }
                                                                                                                                                                            +
                                                                                                                                                                            +    // 初始化最小堆
                                                                                                                                                                            +    h := &MinHeap{}
                                                                                                                                                                            +    heap.Init(h)
                                                                                                                                                                            +
                                                                                                                                                                            +    // 遍歷集合
                                                                                                                                                                            +    for _, num := range nums {
                                                                                                                                                                            +        if h.Len() < k {
                                                                                                                                                                            +            heap.Push(h, num)
                                                                                                                                                                            +        } else if num > (*h)[0] {
                                                                                                                                                                            +            heap.Pop(h)
                                                                                                                                                                            +            heap.Push(h, num)
                                                                                                                                                                            +        }
                                                                                                                                                                            +    }
                                                                                                                                                                            +    // fmt.Println(h)
                                                                                                                                                                            +
                                                                                                                                                                            +    return (*h)[0]
                                                                                                                                                                            +}
                                                                                                                                                                            +
                                                                                                                                                                            +// 自定義最小 Heap 結構體
                                                                                                                                                                            +type MinHeap []int
                                                                                                                                                                            +
                                                                                                                                                                            +func (h MinHeap) Len() int {
                                                                                                                                                                            +    return len(h)
                                                                                                                                                                            +}
                                                                                                                                                                            +func (h MinHeap) Less(i, j int) bool {
                                                                                                                                                                            +    // 小到大排序
                                                                                                                                                                            +    return h[i] < h[j]
                                                                                                                                                                            +}
                                                                                                                                                                            +func (h MinHeap) Swap(i, j int) {
                                                                                                                                                                            +    h[i], h[j] = h[j], h[i]
                                                                                                                                                                            +}
                                                                                                                                                                            +
                                                                                                                                                                            +// Push 和 Pop 方法需要使用指針,因為它們會修改 slice 的長度,而不僅僅只內容。
                                                                                                                                                                            +func (h *MinHeap) Push(x interface{}) {
                                                                                                                                                                            +    *h = append(*h, x.(int))
                                                                                                                                                                            +}
                                                                                                                                                                            +func (h *MinHeap) Pop() interface{} {
                                                                                                                                                                            +    old := *h
                                                                                                                                                                            +    n := len(old)
                                                                                                                                                                            +    x := old[n-1]
                                                                                                                                                                            +    *h = old[:n-1]
                                                                                                                                                                            +    return x
                                                                                                                                                                            +}
                                                                                                                                                                            +
                                                                                                                                                                            +// 解法二:先Sort,再取第k個, 最快!
                                                                                                                                                                            +func FindKthLargestSort(nums []int, k int) int {
                                                                                                                                                                            +    sort.Ints(nums)
                                                                                                                                                                            +    return nums[len(nums)-k]
                                                                                                                                                                            +}
                                                                                                                                                                            +
                                                                                                                                                                            +

                                                                                                                                                                            Benchmark

                                                                                                                                                                            +
                                                                                                                                                                            goos: darwin
                                                                                                                                                                            +goarch: amd64
                                                                                                                                                                            +pkg: LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array
                                                                                                                                                                            +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                            +BenchmarkFindKthLargestHeap-8            6112726               184.9 ns/op            48 B/op          3 allocs/op
                                                                                                                                                                            +BenchmarkFindKthLargestSort-8           18023403                60.38 ns/op           24 B/op          1 allocs/op
                                                                                                                                                                            +PASS
                                                                                                                                                                            +ok      LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array    3.383s
                                                                                                                                                                            +
                                                                                                                                                                            +
                                                                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                            + +
                                                                                                                                                                            + +
                                                                                                                                                                            +
                                                                                                                                                                            +
                                                                                                                                                                            + +

                                                                                                                                                                            results matching ""

                                                                                                                                                                            +
                                                                                                                                                                              + +
                                                                                                                                                                              +
                                                                                                                                                                              + +

                                                                                                                                                                              No results matching ""

                                                                                                                                                                              + +
                                                                                                                                                                              +
                                                                                                                                                                              +
                                                                                                                                                                              + +
                                                                                                                                                                              +
                                                                                                                                                                              + +
                                                                                                                                                                              + + + + + + + + + + +
                                                                                                                                                                              + + +
                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0215.Kth-Largest-Element-in-an-Array/main.go b/Leetcode/0215.Kth-Largest-Element-in-an-Array/main.go new file mode 100644 index 000000000..ef678b0d1 --- /dev/null +++ b/Leetcode/0215.Kth-Largest-Element-in-an-Array/main.go @@ -0,0 +1,66 @@ +package kthlargestelementinanarray + +import ( + "container/heap" + "sort" +) + +// ่งฃๆณ•ไธ€๏ผš็”จHeap่ณ‡ๆ–™็ตๆง‹ +// container/heapๅŒ…ๅฏไปฅ็”จๆฅๆง‹้€ ๅ„ชๅ…ˆ็ดšQueueใ€‚ +// Heap(ๅ †็ฉ)ๅ…ถๅฏฆๆ˜ฏไธ€ๅ€‹Complete Binary Tree(ๅฎŒๅ…จไบŒๅ…ƒๆจน). +// Go็š„Heap็‰นๆ€งๆ˜ฏ ๅ„ๅ€‹็ฏ€้ปž้ƒฝ่‡ชๅทฑๆ˜ฏๅ…ถๅญๆจน็š„ๆ น, ไธ”ๅ€ผๆ˜ฏๆœ€ๅฐ็š„(index = 0 ็š„ๅ€ผๆ˜ฏๆœ€ๅฐ็š„). +// ๅŒๅ€‹ๆ น็ฏ€้ปž็š„ๅทฆๅญๆจน็š„ๅ€ผๆœƒๅฐๆ–ผๅณๅญๆจน +func FindKthLargestHeap(nums []int, k int) int { + if k <= 0 || k > len(nums) { + return 0 + } + + // ๅˆๅง‹ๅŒ–ๆœ€ๅฐๅ † + h := &MinHeap{} + heap.Init(h) + + // ้ๆญท้›†ๅˆ + for _, num := range nums { + if h.Len() < k { + heap.Push(h, num) + } else if num > (*h)[0] { + heap.Pop(h) + heap.Push(h, num) + } + } + // fmt.Println(h) + + return (*h)[0] +} + +// ่‡ชๅฎš็พฉๆœ€ๅฐ Heap ็ตๆง‹้ซ” +type MinHeap []int + +func (h MinHeap) Len() int { + return len(h) +} +func (h MinHeap) Less(i, j int) bool { + // ๅฐๅˆฐๅคงๆŽ’ๅบ + return h[i] < h[j] +} +func (h MinHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +// Push ๅ’Œ Pop ๆ–นๆณ•้œ€่ฆไฝฟ็”จๆŒ‡้‡๏ผŒๅ› ็‚บๅฎƒๅ€‘ๆœƒไฟฎๆ”น slice ็š„้•ทๅบฆ๏ผŒ่€Œไธๅƒ…ๅƒ…ๅชๅ…งๅฎนใ€‚ +func (h *MinHeap) Push(x interface{}) { + *h = append(*h, x.(int)) +} +func (h *MinHeap) Pop() interface{} { + old := *h + n := len(old) + x := old[n-1] + *h = old[:n-1] + return x +} + +// ่งฃๆณ•ไบŒ๏ผšๅ…ˆSort๏ผŒๅ†ๅ–็ฌฌkๅ€‹, ๆœ€ๅฟซ๏ผ +func FindKthLargestSort(nums []int, k int) int { + sort.Ints(nums) + return nums[len(nums)-k] +} diff --git a/Leetcode/0215.Kth-Largest-Element-in-an-Array/main_test.go b/Leetcode/0215.Kth-Largest-Element-in-an-Array/main_test.go new file mode 100644 index 000000000..57bf1d2f4 --- /dev/null +++ b/Leetcode/0215.Kth-Largest-Element-in-an-Array/main_test.go @@ -0,0 +1,64 @@ +package kthlargestelementinanarray + +import "testing" + +var tests = []struct { + arg1 []int + arg2 int + want int +}{ + { + []int{3, 2, 1, 5, 6, 4}, + 2, + 5, + }, + { + []int{3, 2, 3, 1, 2, 4, 5, 5, 6}, + 4, + 4, + }, +} + +func TestFindKthLargestHeap(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := FindKthLargestHeap(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestFindKthLargestSort(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := FindKthLargestSort(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkFindKthLargestHeap(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FindKthLargestHeap(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkFindKthLargestSort(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FindKthLargestSort(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkFindKthLargestHeap-8 6112726 184.9 ns/op 48 B/op 3 allocs/op +BenchmarkFindKthLargestSort-8 18023403 60.38 ns/op 24 B/op 1 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array 3.383s +*/ diff --git a/Leetcode/0217.Contains-Duplicate/index.html b/Leetcode/0217.Contains-Duplicate/index.html new file mode 100644 index 000000000..2cd23088d --- /dev/null +++ b/Leetcode/0217.Contains-Duplicate/index.html @@ -0,0 +1,3835 @@ + + + + + + + 0217.Contains-Duplicate ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                              +
                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                              + +
                                                                                                                                                                              + +
                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                              +
                                                                                                                                                                              + +
                                                                                                                                                                              +
                                                                                                                                                                              + +
                                                                                                                                                                              + +

                                                                                                                                                                              0217.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
                                                                                                                                                                              +

                                                                                                                                                                              Example 2:

                                                                                                                                                                              +
                                                                                                                                                                              Input: nums = [1,2,3,4]
                                                                                                                                                                              +Output: false
                                                                                                                                                                              +

                                                                                                                                                                              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
                                                                                                                                                                              • +
                                                                                                                                                                              +

                                                                                                                                                                              題目大意

                                                                                                                                                                              +

                                                                                                                                                                              解題思路

                                                                                                                                                                              +

                                                                                                                                                                              來源

                                                                                                                                                                              + +

                                                                                                                                                                              解答

                                                                                                                                                                              +

                                                                                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0217.Contains-Duplicate/main.go

                                                                                                                                                                              +
                                                                                                                                                                              package containsduplicate
                                                                                                                                                                              +
                                                                                                                                                                              +func ContainsDuplicate(nums []int) bool {
                                                                                                                                                                              +    numsMap := make(map[int]bool, len(nums))
                                                                                                                                                                              +    for _, v := range nums {
                                                                                                                                                                              +        if numsMap[v] {
                                                                                                                                                                              +            return true
                                                                                                                                                                              +        }
                                                                                                                                                                              +        numsMap[v] = true
                                                                                                                                                                              +    }
                                                                                                                                                                              +    return false
                                                                                                                                                                              +}
                                                                                                                                                                              +
                                                                                                                                                                              +

                                                                                                                                                                              Benchmark

                                                                                                                                                                              +
                                                                                                                                                                              
                                                                                                                                                                              +
                                                                                                                                                                              +
                                                                                                                                                                              +
                                                                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                              + +
                                                                                                                                                                              + +
                                                                                                                                                                              +
                                                                                                                                                                              +
                                                                                                                                                                              + +

                                                                                                                                                                              results matching ""

                                                                                                                                                                              +
                                                                                                                                                                                + +
                                                                                                                                                                                +
                                                                                                                                                                                + +

                                                                                                                                                                                No results matching ""

                                                                                                                                                                                + +
                                                                                                                                                                                +
                                                                                                                                                                                +
                                                                                                                                                                                + +
                                                                                                                                                                                +
                                                                                                                                                                                + +
                                                                                                                                                                                + + + + + + + + + + +
                                                                                                                                                                                + + +
                                                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0217.Contains-Duplicate/main.go b/Leetcode/0217.Contains-Duplicate/main.go new file mode 100644 index 000000000..7ab3e914c --- /dev/null +++ b/Leetcode/0217.Contains-Duplicate/main.go @@ -0,0 +1,12 @@ +package containsduplicate + +func ContainsDuplicate(nums []int) bool { + numsMap := make(map[int]bool, len(nums)) + for _, v := range nums { + if numsMap[v] { + return true + } + numsMap[v] = true + } + return false +} diff --git a/Leetcode/0217.Contains-Duplicate/main_test.go b/Leetcode/0217.Contains-Duplicate/main_test.go new file mode 100644 index 000000000..7c1e82ad6 --- /dev/null +++ b/Leetcode/0217.Contains-Duplicate/main_test.go @@ -0,0 +1,33 @@ +package containsduplicate + +import "testing" + +var tests = []struct { + input []int + expected bool +}{ + {[]int{1, 2, 3, 1}, true}, // Duplicate element present + {[]int{1, 2, 3, 4}, false}, // No duplicate element + {[]int{1, 1, 1, 3, 3, 4, 3, 2, 4, 2}, true}, // Duplicate element present +} + +func TestContainsDuplicate(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.expected) { + if got := ContainsDuplicate(tt.input); got != tt.expected { + t.Errorf("got = %v, expected = %v", got, tt.expected) + } + } +} + +func BenchmarkContainsDuplicate(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + ContainsDuplicate(tests[0].input) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0226.Invert-Binary-Tree/images/invert1-tree.jpg b/Leetcode/0226.Invert-Binary-Tree/images/invert1-tree.jpg new file mode 100644 index 000000000..d82d93a20 Binary files /dev/null and b/Leetcode/0226.Invert-Binary-Tree/images/invert1-tree.jpg differ diff --git a/Leetcode/0226.Invert-Binary-Tree/images/invert2-tree.jpg b/Leetcode/0226.Invert-Binary-Tree/images/invert2-tree.jpg new file mode 100644 index 000000000..6d4744b5c Binary files /dev/null and b/Leetcode/0226.Invert-Binary-Tree/images/invert2-tree.jpg differ diff --git a/Leetcode/0226.Invert-Binary-Tree/index.html b/Leetcode/0226.Invert-Binary-Tree/index.html new file mode 100644 index 000000000..a25d86c90 --- /dev/null +++ b/Leetcode/0226.Invert-Binary-Tree/index.html @@ -0,0 +1,3908 @@ + + + + + + + 226. Invert Binary Tree ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                +
                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                + +
                                                                                                                                                                                + +
                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                +
                                                                                                                                                                                + +
                                                                                                                                                                                +
                                                                                                                                                                                + +
                                                                                                                                                                                + +

                                                                                                                                                                                226. Invert Binary Tree

                                                                                                                                                                                題目

                                                                                                                                                                                +

                                                                                                                                                                                Given the root of a binary tree, invert the tree, and return its root.

                                                                                                                                                                                +

                                                                                                                                                                                Example 1: +

                                                                                                                                                                                +

                                                                                                                                                                                Input: root = [4,2,7,1,3,6,9] +Output: [4,7,2,9,6,3,1]

                                                                                                                                                                                +

                                                                                                                                                                                Example 2: +

                                                                                                                                                                                +

                                                                                                                                                                                Input: root = [2,1,3] +Output: [2,3,1] +Example 3:

                                                                                                                                                                                +

                                                                                                                                                                                Input: root = [] +Output: []

                                                                                                                                                                                +

                                                                                                                                                                                Constraints:

                                                                                                                                                                                +
                                                                                                                                                                                  +
                                                                                                                                                                                • The number of nodes in the tree is in the range [0, 100].
                                                                                                                                                                                • +
                                                                                                                                                                                • -100 <= Node.val <= 100
                                                                                                                                                                                • +
                                                                                                                                                                                +

                                                                                                                                                                                題目大意

                                                                                                                                                                                +

                                                                                                                                                                                反轉二叉樹

                                                                                                                                                                                +

                                                                                                                                                                                解題思路

                                                                                                                                                                                +

                                                                                                                                                                                用遞歸來解決,先遞歸調用反轉根節點的左children,然後遞歸調用反轉根節點的右children,然後左右交換根節點的左children和右children。 +有點像是BFS

                                                                                                                                                                                +
                                                                                                                                                                                +

                                                                                                                                                                                BFS(廣度優先搜索)則使用隊列(Queue)來實現。在BFS中,您首先處理一個節點,然後將其子節點按某種順序排隊,接著繼續處理隊列的前端節點,直到隊列為空。

                                                                                                                                                                                +
                                                                                                                                                                                +

                                                                                                                                                                                來源

                                                                                                                                                                                + +

                                                                                                                                                                                解答

                                                                                                                                                                                +

                                                                                                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0226.Invert-Binary-Tree/main.go

                                                                                                                                                                                +
                                                                                                                                                                                package invertbinarytree
                                                                                                                                                                                +
                                                                                                                                                                                +import (
                                                                                                                                                                                +    "LeetcodeGolang/Utility/structures"
                                                                                                                                                                                +)
                                                                                                                                                                                +
                                                                                                                                                                                +/**
                                                                                                                                                                                + * Definition for a binary tree node.
                                                                                                                                                                                + * type TreeNode struct {
                                                                                                                                                                                + *     Val int
                                                                                                                                                                                + *     Left *TreeNode
                                                                                                                                                                                + *     Right *TreeNode
                                                                                                                                                                                + * }
                                                                                                                                                                                + */
                                                                                                                                                                                +
                                                                                                                                                                                +// type TreeNode struct {
                                                                                                                                                                                +//     Val   int
                                                                                                                                                                                +//     Left  *TreeNode
                                                                                                                                                                                +//     Right *TreeNode
                                                                                                                                                                                +// }
                                                                                                                                                                                +
                                                                                                                                                                                +func InvertTree(root *structures.TreeNode) *structures.TreeNode {
                                                                                                                                                                                +    if root == nil {
                                                                                                                                                                                +        return nil
                                                                                                                                                                                +    }
                                                                                                                                                                                +
                                                                                                                                                                                +    InvertTree(root.Left)
                                                                                                                                                                                +    InvertTree(root.Right)
                                                                                                                                                                                +
                                                                                                                                                                                +    root.Left, root.Right = root.Right, root.Left
                                                                                                                                                                                +    return root
                                                                                                                                                                                +}
                                                                                                                                                                                +
                                                                                                                                                                                +func InvertTree2(root *structures.TreeNode) *structures.TreeNode {
                                                                                                                                                                                +
                                                                                                                                                                                +    if root != nil {
                                                                                                                                                                                +        root.Left, root.Right = InvertTree2(root.Right), InvertTree2(root.Left)
                                                                                                                                                                                +    }
                                                                                                                                                                                +
                                                                                                                                                                                +    return root
                                                                                                                                                                                +}
                                                                                                                                                                                +
                                                                                                                                                                                +func InvertTree3(root *structures.TreeNode) *structures.TreeNode {
                                                                                                                                                                                +    queue := make([]*structures.TreeNode, 0)
                                                                                                                                                                                +    queue = append(queue, root)
                                                                                                                                                                                +
                                                                                                                                                                                +    for len(queue) > 0 {
                                                                                                                                                                                +        current := queue[0]
                                                                                                                                                                                +        queue = queue[1:]
                                                                                                                                                                                +
                                                                                                                                                                                +        current.Left, current.Right = current.Right, current.Left
                                                                                                                                                                                +
                                                                                                                                                                                +        if current.Left != nil {
                                                                                                                                                                                +            queue = append(queue, current.Left)
                                                                                                                                                                                +        }
                                                                                                                                                                                +
                                                                                                                                                                                +        if current.Right != nil {
                                                                                                                                                                                +            queue = append(queue, current.Right)
                                                                                                                                                                                +        }
                                                                                                                                                                                +    }
                                                                                                                                                                                +    return root
                                                                                                                                                                                +}
                                                                                                                                                                                +
                                                                                                                                                                                +
                                                                                                                                                                                func BuildTree(nums []int, index int) *TreeNode {
                                                                                                                                                                                +    if index >= len(nums) || nums[index] == -1 {
                                                                                                                                                                                +        return nil
                                                                                                                                                                                +    }
                                                                                                                                                                                +    root := &TreeNode{Val: nums[index]}
                                                                                                                                                                                +    root.Left = BuildTree(nums, 2*index+1)
                                                                                                                                                                                +    root.Right = BuildTree(nums, 2*index+2)
                                                                                                                                                                                +    return root
                                                                                                                                                                                +}
                                                                                                                                                                                +
                                                                                                                                                                                +func IntsToTree(nums []int) *TreeNode {
                                                                                                                                                                                +    return BuildTree(nums, 0)
                                                                                                                                                                                +}
                                                                                                                                                                                +
                                                                                                                                                                                +

                                                                                                                                                                                Benchmark

                                                                                                                                                                                +
                                                                                                                                                                                goos: darwin
                                                                                                                                                                                +goarch: amd64
                                                                                                                                                                                +pkg: LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree
                                                                                                                                                                                +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                +BenchmarkInvertTree-8            2533011               398.7 ns/op           168 B/op          7 allocs/op
                                                                                                                                                                                +BenchmarkInvertTree2-8           2667645               392.4 ns/op           168 B/op          7 allocs/op
                                                                                                                                                                                +BenchmarkInvertTree3-8           1403001               727.5 ns/op           296 B/op         13 allocs/op
                                                                                                                                                                                +PASS
                                                                                                                                                                                +ok      LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree 4.889s
                                                                                                                                                                                +
                                                                                                                                                                                +
                                                                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                + +
                                                                                                                                                                                + +
                                                                                                                                                                                +
                                                                                                                                                                                +
                                                                                                                                                                                + +

                                                                                                                                                                                results matching ""

                                                                                                                                                                                +
                                                                                                                                                                                  + +
                                                                                                                                                                                  +
                                                                                                                                                                                  + +

                                                                                                                                                                                  No results matching ""

                                                                                                                                                                                  + +
                                                                                                                                                                                  +
                                                                                                                                                                                  +
                                                                                                                                                                                  + +
                                                                                                                                                                                  +
                                                                                                                                                                                  + +
                                                                                                                                                                                  + + + + + + +
                                                                                                                                                                                  + + +
                                                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0226.Invert-Binary-Tree/main.go b/Leetcode/0226.Invert-Binary-Tree/main.go new file mode 100644 index 000000000..07d452d39 --- /dev/null +++ b/Leetcode/0226.Invert-Binary-Tree/main.go @@ -0,0 +1,62 @@ +package invertbinarytree + +import ( + "LeetcodeGolang/Utility/structures" +) + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +// type TreeNode struct { +// Val int +// Left *TreeNode +// Right *TreeNode +// } + +func InvertTree(root *structures.TreeNode) *structures.TreeNode { + if root == nil { + return nil + } + + InvertTree(root.Left) + InvertTree(root.Right) + + root.Left, root.Right = root.Right, root.Left + return root +} + +func InvertTree2(root *structures.TreeNode) *structures.TreeNode { + + if root != nil { + root.Left, root.Right = InvertTree2(root.Right), InvertTree2(root.Left) + } + + return root +} + +func InvertTree3(root *structures.TreeNode) *structures.TreeNode { + queue := make([]*structures.TreeNode, 0) + queue = append(queue, root) + + for len(queue) > 0 { + current := queue[0] + queue = queue[1:] + + current.Left, current.Right = current.Right, current.Left + + if current.Left != nil { + queue = append(queue, current.Left) + } + + if current.Right != nil { + queue = append(queue, current.Right) + } + } + return root +} diff --git a/Leetcode/0226.Invert-Binary-Tree/main_test.go b/Leetcode/0226.Invert-Binary-Tree/main_test.go new file mode 100644 index 000000000..77e0cf0f2 --- /dev/null +++ b/Leetcode/0226.Invert-Binary-Tree/main_test.go @@ -0,0 +1,87 @@ +package invertbinarytree + +import ( + "LeetcodeGolang/Utility/structures" + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + want []int +}{ + { + []int{4, 2, 7, 1, 3, 6, 9}, + []int{4, 7, 2, 9, 6, 3, 1}, + }, +} + +func TestInvertTree(t *testing.T) { + for _, tt := range tests { + tree := structures.IntsToTree(tt.arg1) + got := InvertTree(tree) + treeWant := structures.IntsToTree(tt.want) + if !reflect.DeepEqual(got, treeWant) { + t.Errorf("got = %v, want = %v", got, treeWant) + } + } +} + +func TestInvertTree2(t *testing.T) { + for _, tt := range tests { + tree := structures.IntsToTree(tt.arg1) + got := InvertTree2(tree) + treeWant := structures.IntsToTree(tt.want) + if !reflect.DeepEqual(got, treeWant) { + t.Errorf("got = %v, want = %v", got, treeWant) + } + } +} + +func TestInvertTree3(t *testing.T) { + for _, tt := range tests { + tree := structures.IntsToTree(tt.arg1) + got := InvertTree3(tree) + treeWant := structures.IntsToTree(tt.want) + if !reflect.DeepEqual(got, treeWant) { + t.Errorf("got = %v, want = %v", got, treeWant) + } + } +} + +func BenchmarkInvertTree(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + tree := structures.IntsToTree(tests[0].arg1) + InvertTree(tree) + } +} + +func BenchmarkInvertTree2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + tree := structures.IntsToTree(tests[0].arg1) + InvertTree2(tree) + } +} + +func BenchmarkInvertTree3(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + tree := structures.IntsToTree(tests[0].arg1) + InvertTree3(tree) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkInvertTree-8 2533011 398.7 ns/op 168 B/op 7 allocs/op +BenchmarkInvertTree2-8 2667645 392.4 ns/op 168 B/op 7 allocs/op +BenchmarkInvertTree3-8 1403001 727.5 ns/op 296 B/op 13 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree 4.889s +*/ diff --git a/Leetcode/0238.Product-of-Array-Except-Self/index.html b/Leetcode/0238.Product-of-Array-Except-Self/index.html new file mode 100644 index 000000000..c8e4cd995 --- /dev/null +++ b/Leetcode/0238.Product-of-Array-Except-Self/index.html @@ -0,0 +1,3873 @@ + + + + + + + 238. Product of Array Except Self ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                  +
                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                  + +
                                                                                                                                                                                  + +
                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                  +
                                                                                                                                                                                  + +
                                                                                                                                                                                  +
                                                                                                                                                                                  + +
                                                                                                                                                                                  + +

                                                                                                                                                                                  238. Product of Array Except Self

                                                                                                                                                                                  題目

                                                                                                                                                                                  +

                                                                                                                                                                                  Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

                                                                                                                                                                                  +

                                                                                                                                                                                  The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

                                                                                                                                                                                  +

                                                                                                                                                                                  You must write an algorithm that runs in O(n) time and without using the division operation.

                                                                                                                                                                                  +

                                                                                                                                                                                  Example 1:

                                                                                                                                                                                  +

                                                                                                                                                                                  Input: nums = [1,2,3,4] +Output: [24,12,8,6] +Example 2:

                                                                                                                                                                                  +

                                                                                                                                                                                  Input: nums = [-1,1,0,-3,3] +Output: [0,0,9,0,0]

                                                                                                                                                                                  +

                                                                                                                                                                                  Constraints:

                                                                                                                                                                                  +

                                                                                                                                                                                  2 <= nums.length <= 105 +-30 <= nums[i] <= 30 +The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

                                                                                                                                                                                  +

                                                                                                                                                                                  Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

                                                                                                                                                                                  +

                                                                                                                                                                                  題目大意

                                                                                                                                                                                  +

                                                                                                                                                                                  解題思路

                                                                                                                                                                                  +

                                                                                                                                                                                  Big O

                                                                                                                                                                                  +

                                                                                                                                                                                  時間複雜 : O(n) +空間複雜 : ``

                                                                                                                                                                                  +

                                                                                                                                                                                  來源

                                                                                                                                                                                  + +

                                                                                                                                                                                  解答

                                                                                                                                                                                  +

                                                                                                                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0238.Product-of-Array-Except-Self/main.go

                                                                                                                                                                                  +
                                                                                                                                                                                  package productofarrayexceptself
                                                                                                                                                                                  +
                                                                                                                                                                                  +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                                                  +func productExceptSelf(nums []int) []int {
                                                                                                                                                                                  +    result, left, right := make([]int, len(nums)), make([]int, len(nums)), make([]int, len(nums))
                                                                                                                                                                                  +
                                                                                                                                                                                  +    // left 為左側所有的成績
                                                                                                                                                                                  +    // 索引為'0' 的元素, 因為左側沒有元素,所以left[0]=1
                                                                                                                                                                                  +    left[0] = 1
                                                                                                                                                                                  +    for i := 1; i < len(nums); i++ {
                                                                                                                                                                                  +        left[i] = left[i-1] * nums[i-1]
                                                                                                                                                                                  +    }
                                                                                                                                                                                  +
                                                                                                                                                                                  +    right[len(nums)-1] = 1
                                                                                                                                                                                  +    for i := len(nums) - 2; i >= 0; i-- {
                                                                                                                                                                                  +        right[i] = right[i+1] * nums[i+1]
                                                                                                                                                                                  +    }
                                                                                                                                                                                  +
                                                                                                                                                                                  +    for i := 0; i < len(nums); i++ {
                                                                                                                                                                                  +        result[i] = left[i] * right[i]
                                                                                                                                                                                  +    }
                                                                                                                                                                                  +    return result
                                                                                                                                                                                  +}
                                                                                                                                                                                  +
                                                                                                                                                                                  +func productExceptSelf2(nums []int) []int {
                                                                                                                                                                                  +    result := make([]int, len(nums))
                                                                                                                                                                                  +
                                                                                                                                                                                  +    result[0] = 1
                                                                                                                                                                                  +    for i := 1; i < len(nums); i++ {
                                                                                                                                                                                  +        result[i] = result[i-1] * nums[i-1]
                                                                                                                                                                                  +    }
                                                                                                                                                                                  +
                                                                                                                                                                                  +    rightProduct := 1
                                                                                                                                                                                  +    for i := len(nums) - 1; i >= 0; i-- {
                                                                                                                                                                                  +        result[i] = result[i] * rightProduct
                                                                                                                                                                                  +        rightProduct = rightProduct * nums[i]
                                                                                                                                                                                  +    }
                                                                                                                                                                                  +
                                                                                                                                                                                  +    return result
                                                                                                                                                                                  +}
                                                                                                                                                                                  +
                                                                                                                                                                                  +

                                                                                                                                                                                  Benchmark

                                                                                                                                                                                  +
                                                                                                                                                                                  go test -benchmem -run=none LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self -bench=.
                                                                                                                                                                                  +goos: darwin
                                                                                                                                                                                  +goarch: amd64
                                                                                                                                                                                  +pkg: LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self
                                                                                                                                                                                  +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                  +BenchmarkProductExceptSelf-8            12772174               158.4 ns/op            96 B/op          3 allocs/op
                                                                                                                                                                                  +BenchmarkProductExceptSelf2-8           32292304                63.74 ns/op           32 B/op          1 allocs/op
                                                                                                                                                                                  +PASS
                                                                                                                                                                                  +ok      LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self       4.228s
                                                                                                                                                                                  +
                                                                                                                                                                                  +
                                                                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                  + +
                                                                                                                                                                                  + +
                                                                                                                                                                                  +
                                                                                                                                                                                  +
                                                                                                                                                                                  + +

                                                                                                                                                                                  results matching ""

                                                                                                                                                                                  +
                                                                                                                                                                                    + +
                                                                                                                                                                                    +
                                                                                                                                                                                    + +

                                                                                                                                                                                    No results matching ""

                                                                                                                                                                                    + +
                                                                                                                                                                                    +
                                                                                                                                                                                    +
                                                                                                                                                                                    + +
                                                                                                                                                                                    +
                                                                                                                                                                                    + +
                                                                                                                                                                                    + + + + + + + + + + +
                                                                                                                                                                                    + + +
                                                                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0238.Product-of-Array-Except-Self/main.go b/Leetcode/0238.Product-of-Array-Except-Self/main.go new file mode 100644 index 000000000..872fbac2b --- /dev/null +++ b/Leetcode/0238.Product-of-Array-Except-Self/main.go @@ -0,0 +1,40 @@ +package productofarrayexceptself + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +func productExceptSelf(nums []int) []int { + result, left, right := make([]int, len(nums)), make([]int, len(nums)), make([]int, len(nums)) + + // left ็‚บๅทฆๅดๆ‰€ๆœ‰็š„ๆˆ็ธพ + // ็ดขๅผ•็‚บ'0' ็š„ๅ…ƒ็ด , ๅ› ็‚บๅทฆๅดๆฒ’ๆœ‰ๅ…ƒ็ด ,ๆ‰€ไปฅleft[0]=1 + left[0] = 1 + for i := 1; i < len(nums); i++ { + left[i] = left[i-1] * nums[i-1] + } + + right[len(nums)-1] = 1 + for i := len(nums) - 2; i >= 0; i-- { + right[i] = right[i+1] * nums[i+1] + } + + for i := 0; i < len(nums); i++ { + result[i] = left[i] * right[i] + } + return result +} + +func productExceptSelf2(nums []int) []int { + result := make([]int, len(nums)) + + result[0] = 1 + for i := 1; i < len(nums); i++ { + result[i] = result[i-1] * nums[i-1] + } + + rightProduct := 1 + for i := len(nums) - 1; i >= 0; i-- { + result[i] = result[i] * rightProduct + rightProduct = rightProduct * nums[i] + } + + return result +} diff --git a/Leetcode/0238.Product-of-Array-Except-Self/main_test.go b/Leetcode/0238.Product-of-Array-Except-Self/main_test.go new file mode 100644 index 000000000..bb6c63fbc --- /dev/null +++ b/Leetcode/0238.Product-of-Array-Except-Self/main_test.go @@ -0,0 +1,60 @@ +package productofarrayexceptself + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + want []int +}{ + { + []int{1, 2, 3, 4}, + []int{24, 12, 8, 6}, + }, +} + +func TestProductExceptSelf(t *testing.T) { + for _, tt := range tests { + if got := productExceptSelf(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // if got := productExceptSelf(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkProductExceptSelf(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + productExceptSelf(tests[0].arg1) + } +} + +func TestProductExceptSelf2(t *testing.T) { + for _, tt := range tests { + if got := productExceptSelf2(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // if got := productExceptSelf2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkProductExceptSelf2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + productExceptSelf2(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkProductExceptSelf-8 12772174 158.4 ns/op 96 B/op 3 allocs/op +BenchmarkProductExceptSelf2-8 32292304 63.74 ns/op 32 B/op 1 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self 4.228s +*/ diff --git a/Leetcode/0242.Valid-Anagram/index.html b/Leetcode/0242.Valid-Anagram/index.html new file mode 100644 index 000000000..8f0d86fc6 --- /dev/null +++ b/Leetcode/0242.Valid-Anagram/index.html @@ -0,0 +1,3875 @@ + + + + + + + 0242.Valid-Anagram ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                    +
                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                    + +
                                                                                                                                                                                    + +
                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                    +
                                                                                                                                                                                    + +
                                                                                                                                                                                    +
                                                                                                                                                                                    + +
                                                                                                                                                                                    + +

                                                                                                                                                                                    0242.Valid-Anagram

                                                                                                                                                                                    驗證回文串

                                                                                                                                                                                    +

                                                                                                                                                                                    題目

                                                                                                                                                                                    +

                                                                                                                                                                                    Given two strings s and t, return true if t is an anagram of s, and false otherwise.

                                                                                                                                                                                    +

                                                                                                                                                                                    An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

                                                                                                                                                                                    +

                                                                                                                                                                                    Example 1:

                                                                                                                                                                                    +

                                                                                                                                                                                    Input: s = "anagram", t = "nagaram" +Output: true +Example 2:

                                                                                                                                                                                    +

                                                                                                                                                                                    Input: s = "rat", t = "car" +Output: false

                                                                                                                                                                                    +

                                                                                                                                                                                    Constraints:

                                                                                                                                                                                    +

                                                                                                                                                                                    1 <= s.length, t.length <= 5 * 104 +s and t consist of lowercase English letters.

                                                                                                                                                                                    +

                                                                                                                                                                                    Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

                                                                                                                                                                                    +
                                                                                                                                                                                    +

                                                                                                                                                                                    我們使用 rune 數據類型來處理 Unicode 字元,並使用 map[rune]int 來統計這些字符的出現次數。其餘的邏輯保持不變。

                                                                                                                                                                                    +
                                                                                                                                                                                    +

                                                                                                                                                                                    題目大意

                                                                                                                                                                                    +

                                                                                                                                                                                    解題思路

                                                                                                                                                                                    +

                                                                                                                                                                                    只要先把所有字符轉換成小寫,並過濾掉空格和標點這類字符,然後對剩下的字符執行 數組雙指針技巧匯總 中提到的兩端向中心的雙指針演算法即可

                                                                                                                                                                                    +

                                                                                                                                                                                    來源

                                                                                                                                                                                    + +

                                                                                                                                                                                    解答

                                                                                                                                                                                    +

                                                                                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0242.Valid-Anagram/main.go

                                                                                                                                                                                    +
                                                                                                                                                                                    package validanagram
                                                                                                                                                                                    +
                                                                                                                                                                                    +func IsAnagram(s string, t string) bool {
                                                                                                                                                                                    +    if len(s) != len(t) {
                                                                                                                                                                                    +        return false
                                                                                                                                                                                    +    }
                                                                                                                                                                                    +
                                                                                                                                                                                    +    record := make(map[rune]int, len(s))
                                                                                                                                                                                    +
                                                                                                                                                                                    +    for _, v := range s {
                                                                                                                                                                                    +        record[v]++
                                                                                                                                                                                    +    }
                                                                                                                                                                                    +    for _, v := range t {
                                                                                                                                                                                    +        record[v]--
                                                                                                                                                                                    +        if record[v] < 0 {
                                                                                                                                                                                    +            return false
                                                                                                                                                                                    +        }
                                                                                                                                                                                    +    }
                                                                                                                                                                                    +    return true
                                                                                                                                                                                    +}
                                                                                                                                                                                    +
                                                                                                                                                                                    +func IsAnagram2(s string, t string) bool {
                                                                                                                                                                                    +    if len(s) != len(t) {
                                                                                                                                                                                    +        return false
                                                                                                                                                                                    +    }
                                                                                                                                                                                    +
                                                                                                                                                                                    +    record := make(map[rune]int, len(s))
                                                                                                                                                                                    +
                                                                                                                                                                                    +    for _, v := range s {
                                                                                                                                                                                    +        record[v]++
                                                                                                                                                                                    +    }
                                                                                                                                                                                    +    for _, v := range t {
                                                                                                                                                                                    +        record[v]--
                                                                                                                                                                                    +    }
                                                                                                                                                                                    +
                                                                                                                                                                                    +    for _, v := range record {
                                                                                                                                                                                    +        if v != 0 {
                                                                                                                                                                                    +            return false
                                                                                                                                                                                    +        }
                                                                                                                                                                                    +    }
                                                                                                                                                                                    +    return true
                                                                                                                                                                                    +}
                                                                                                                                                                                    +
                                                                                                                                                                                    +

                                                                                                                                                                                    Benchmark

                                                                                                                                                                                    +
                                                                                                                                                                                    goos: darwin
                                                                                                                                                                                    +goarch: amd64
                                                                                                                                                                                    +pkg: LeetcodeGolang/Leetcode/0242.Valid-Anagram
                                                                                                                                                                                    +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                    +BenchmarkIsAnagram-8             6703497               276.3 ns/op             0 B/op          0 allocs/op
                                                                                                                                                                                    +BenchmarkIsAnagram2-8            3660909               318.9 ns/op            48 B/op          2 allocs/op
                                                                                                                                                                                    +PASS
                                                                                                                                                                                    +ok      LeetcodeGolang/Leetcode/0242.Valid-Anagram      4.498s
                                                                                                                                                                                    +
                                                                                                                                                                                    +
                                                                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                    + +
                                                                                                                                                                                    + +
                                                                                                                                                                                    +
                                                                                                                                                                                    +
                                                                                                                                                                                    + +

                                                                                                                                                                                    results matching ""

                                                                                                                                                                                    +
                                                                                                                                                                                      + +
                                                                                                                                                                                      +
                                                                                                                                                                                      + +

                                                                                                                                                                                      No results matching ""

                                                                                                                                                                                      + +
                                                                                                                                                                                      +
                                                                                                                                                                                      +
                                                                                                                                                                                      + +
                                                                                                                                                                                      +
                                                                                                                                                                                      + +
                                                                                                                                                                                      + + + + + + + + + + +
                                                                                                                                                                                      + + +
                                                                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0242.Valid-Anagram/main.go b/Leetcode/0242.Valid-Anagram/main.go new file mode 100644 index 000000000..f9afda1b0 --- /dev/null +++ b/Leetcode/0242.Valid-Anagram/main.go @@ -0,0 +1,42 @@ +package validanagram + +func IsAnagram(s string, t string) bool { + if len(s) != len(t) { + return false + } + + record := make(map[rune]int, len(s)) + + for _, v := range s { + record[v]++ + } + for _, v := range t { + record[v]-- + if record[v] < 0 { + return false + } + } + return true +} + +func IsAnagram2(s string, t string) bool { + if len(s) != len(t) { + return false + } + + record := make(map[rune]int, len(s)) + + for _, v := range s { + record[v]++ + } + for _, v := range t { + record[v]-- + } + + for _, v := range record { + if v != 0 { + return false + } + } + return true +} diff --git a/Leetcode/0242.Valid-Anagram/main_test.go b/Leetcode/0242.Valid-Anagram/main_test.go new file mode 100644 index 000000000..e552c7609 --- /dev/null +++ b/Leetcode/0242.Valid-Anagram/main_test.go @@ -0,0 +1,64 @@ +package validanagram + +import "testing" + +var tests = []struct { + s string + t string + expected bool +}{ + {"anagram", "nagaram", true}, // ๆ˜ฏๆœ‰ๆ•ˆ็š„ๅญ—ๆฏ็•ฐไฝ่ฉž + {"rat", "car", false}, // ไธๆ˜ฏๆœ‰ๆ•ˆ็š„ๅญ—ๆฏ็•ฐไฝ่ฉž + {"listen", "silent", true}, // ๆ˜ฏๆœ‰ๆ•ˆ็š„ๅญ—ๆฏ็•ฐไฝ่ฉž + {"hello", "world", false}, // ไธๆ˜ฏๆœ‰ๆ•ˆ็š„ๅญ—ๆฏ็•ฐไฝ่ฉž +} + +func TestIsAnagram(t *testing.T) { + + for _, test := range tests { + result := IsAnagram(test.s, test.t) + if result != test.expected { + t.Errorf("s: %s, t: %s, Expected: %v, Got: %v", test.s, test.t, test.expected, result) + } + } +} + +func TestIsAnagram2(t *testing.T) { + + for _, test := range tests { + result := IsAnagram2(test.s, test.t) + if result != test.expected { + t.Errorf("s: %s, t: %s, Expected: %v, Got: %v", test.s, test.t, test.expected, result) + } + } +} + +func BenchmarkIsAnagram(b *testing.B) { + s := "anagram" + t := "nagaram" + b.ResetTimer() + for i := 0; i < b.N; i++ { + IsAnagram(s, t) + } +} + +func BenchmarkIsAnagram2(b *testing.B) { + s := "anagram" + t := "nagaram" + b.ResetTimer() + for i := 0; i < b.N; i++ { + IsAnagram2(s, t) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0242.Valid-Anagram -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0242.Valid-Anagram +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkIsAnagram-8 6703497 276.3 ns/op 0 B/op 0 allocs/op +BenchmarkIsAnagram2-8 3660909 318.9 ns/op 48 B/op 2 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0242.Valid-Anagram 4.498s +*/ diff --git a/Leetcode/0283.Move-Zeroes/index.html b/Leetcode/0283.Move-Zeroes/index.html new file mode 100644 index 000000000..2d219a512 --- /dev/null +++ b/Leetcode/0283.Move-Zeroes/index.html @@ -0,0 +1,3856 @@ + + + + + + + 0283. Move Zeroes ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                      +
                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                      + +
                                                                                                                                                                                      + +
                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                      +
                                                                                                                                                                                      + +
                                                                                                                                                                                      +
                                                                                                                                                                                      + +
                                                                                                                                                                                      + +

                                                                                                                                                                                      283. Move Zeroes

                                                                                                                                                                                      題目

                                                                                                                                                                                      +

                                                                                                                                                                                      Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

                                                                                                                                                                                      +

                                                                                                                                                                                      Note that you must do this in-place without making a copy of the array.

                                                                                                                                                                                      +

                                                                                                                                                                                      Example 1:

                                                                                                                                                                                      +
                                                                                                                                                                                      Input: nums = [0,1,0,3,12]
                                                                                                                                                                                      +Output: [1,3,12,0,0]
                                                                                                                                                                                      +

                                                                                                                                                                                      Example 2:

                                                                                                                                                                                      +
                                                                                                                                                                                      Input: nums = [0]
                                                                                                                                                                                      +Output: [0]
                                                                                                                                                                                      +

                                                                                                                                                                                      Constraints:

                                                                                                                                                                                      +
                                                                                                                                                                                        +
                                                                                                                                                                                      • 1 <= nums.length <= 104
                                                                                                                                                                                      • +
                                                                                                                                                                                      • -231 <= nums[i] <= 231 - 1
                                                                                                                                                                                      • +
                                                                                                                                                                                      +

                                                                                                                                                                                      Follow up: Could you minimize the total number of operations done?

                                                                                                                                                                                      +

                                                                                                                                                                                      題目大意

                                                                                                                                                                                      +

                                                                                                                                                                                      題目要求不能利用額外的輔助空間,將數字組中 0 元素都移到數字組的末尾,並與維持所有非 0 元素的相對位置。

                                                                                                                                                                                      +

                                                                                                                                                                                      解題思路

                                                                                                                                                                                      +
                                                                                                                                                                                        +
                                                                                                                                                                                      1. 非零交換數據, 左右指針都往右移
                                                                                                                                                                                      2. +
                                                                                                                                                                                      3. 零, 右指針右移
                                                                                                                                                                                      4. +
                                                                                                                                                                                      +

                                                                                                                                                                                      來源

                                                                                                                                                                                      + +

                                                                                                                                                                                      解答

                                                                                                                                                                                      +

                                                                                                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0283.Move-Zeroes/main.go

                                                                                                                                                                                      +
                                                                                                                                                                                      package movezeroes
                                                                                                                                                                                      +
                                                                                                                                                                                      +// 時間O(n^2)
                                                                                                                                                                                      +func MoveZeroes(nums []int) {
                                                                                                                                                                                      +    for i := 0; i < len(nums); i++ {
                                                                                                                                                                                      +        if nums[i] == 0 {
                                                                                                                                                                                      +            for j := i + 1; j < len(nums); j++ {
                                                                                                                                                                                      +                if nums[j] != 0 {
                                                                                                                                                                                      +                    nums[i], nums[j] = nums[j], nums[i]
                                                                                                                                                                                      +                    break
                                                                                                                                                                                      +                }
                                                                                                                                                                                      +            }
                                                                                                                                                                                      +        }
                                                                                                                                                                                      +    }
                                                                                                                                                                                      +}
                                                                                                                                                                                      +
                                                                                                                                                                                      +// 時間O(n), 空間O(1)
                                                                                                                                                                                      +func MoveZeroes2point(nums []int) {
                                                                                                                                                                                      +    j := 0
                                                                                                                                                                                      +    for i := 0; i < len(nums); i++ {
                                                                                                                                                                                      +        if nums[i] != 0 {
                                                                                                                                                                                      +            if i != j {
                                                                                                                                                                                      +                nums[i], nums[j] = nums[j], nums[i]
                                                                                                                                                                                      +            }
                                                                                                                                                                                      +            j++
                                                                                                                                                                                      +        }
                                                                                                                                                                                      +    }
                                                                                                                                                                                      +}
                                                                                                                                                                                      +
                                                                                                                                                                                      +

                                                                                                                                                                                      Benchmark

                                                                                                                                                                                      +
                                                                                                                                                                                      goos: darwin
                                                                                                                                                                                      +goarch: amd64
                                                                                                                                                                                      +pkg: LeetcodeGolang/Leetcode/0283.Move-Zeroes
                                                                                                                                                                                      +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
                                                                                                                                                                                      +BenchmarkMoveZeroes-4           145544966                9.164 ns/op           0 B/op          0 allocs/op
                                                                                                                                                                                      +BenchmarkMoveZeroes2point-4     183269922                6.149 ns/op           0 B/op          0 allocs/op
                                                                                                                                                                                      +PASS
                                                                                                                                                                                      +ok      LeetcodeGolang/Leetcode/0283.Move-Zeroes        3.975s
                                                                                                                                                                                      +
                                                                                                                                                                                      +
                                                                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                      + +
                                                                                                                                                                                      + +
                                                                                                                                                                                      +
                                                                                                                                                                                      +
                                                                                                                                                                                      + +

                                                                                                                                                                                      results matching ""

                                                                                                                                                                                      +
                                                                                                                                                                                        + +
                                                                                                                                                                                        +
                                                                                                                                                                                        + +

                                                                                                                                                                                        No results matching ""

                                                                                                                                                                                        + +
                                                                                                                                                                                        +
                                                                                                                                                                                        +
                                                                                                                                                                                        + +
                                                                                                                                                                                        +
                                                                                                                                                                                        + +
                                                                                                                                                                                        + + + + + + +
                                                                                                                                                                                        + + +
                                                                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0283.Move-Zeroes/main.go b/Leetcode/0283.Move-Zeroes/main.go new file mode 100644 index 000000000..2662b3e56 --- /dev/null +++ b/Leetcode/0283.Move-Zeroes/main.go @@ -0,0 +1,28 @@ +package movezeroes + +// ๆ™‚้–“O(n^2) +func MoveZeroes(nums []int) { + for i := 0; i < len(nums); i++ { + if nums[i] == 0 { + for j := i + 1; j < len(nums); j++ { + if nums[j] != 0 { + nums[i], nums[j] = nums[j], nums[i] + break + } + } + } + } +} + +// ๆ™‚้–“O(n), ็ฉบ้–“O(1) +func MoveZeroes2point(nums []int) { + j := 0 + for i := 0; i < len(nums); i++ { + if nums[i] != 0 { + if i != j { + nums[i], nums[j] = nums[j], nums[i] + } + j++ + } + } +} diff --git a/Leetcode/0283.Move-Zeroes/main_test.go b/Leetcode/0283.Move-Zeroes/main_test.go new file mode 100644 index 000000000..729217555 --- /dev/null +++ b/Leetcode/0283.Move-Zeroes/main_test.go @@ -0,0 +1,64 @@ +package movezeroes + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + want []int +}{ + { + []int{0, 1, 0, 3, 12}, + []int{1, 3, 12, 0, 0}, + }, + { + []int{0}, + []int{0}, + }, +} + +func TestMoveZeroes(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if MoveZeroes(tt.arg1); !reflect.DeepEqual(tt.arg1, tt.want) { + t.Errorf("got = %v, want = %v", tt.arg1, tt.want) + } + } +} + +func TestMoveZeroes2point(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if MoveZeroes2point(tt.arg1); !reflect.DeepEqual(tt.arg1, tt.want) { + t.Errorf("got = %v, want = %v", tt.arg1, tt.want) + } + } +} + +func BenchmarkMoveZeroes(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MoveZeroes(tests[0].arg1) + } +} + +func BenchmarkMoveZeroes2point(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MoveZeroes2point(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0283.Move-Zeroes -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0283.Move-Zeroes +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkMoveZeroes-4 145544966 9.164 ns/op 0 B/op 0 allocs/op +BenchmarkMoveZeroes2point-4 183269922 6.149 ns/op 0 B/op 0 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0283.Move-Zeroes 3.975s +*/ diff --git a/Leetcode/0300.Longest-Increasing-Subsequence/index.html b/Leetcode/0300.Longest-Increasing-Subsequence/index.html new file mode 100644 index 000000000..a8219a986 --- /dev/null +++ b/Leetcode/0300.Longest-Increasing-Subsequence/index.html @@ -0,0 +1,3934 @@ + + + + + + + 0300.Longest Increasing Subsequence ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                        +
                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                        + +
                                                                                                                                                                                        + +
                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                        +
                                                                                                                                                                                        + +
                                                                                                                                                                                        +
                                                                                                                                                                                        + +
                                                                                                                                                                                        + +

                                                                                                                                                                                        300.Longest-Increasing-Subsequence

                                                                                                                                                                                        最長遞增子序列(Longest Increasing Subsequence, LIS)

                                                                                                                                                                                        +

                                                                                                                                                                                        題目

                                                                                                                                                                                        +

                                                                                                                                                                                        Given an integer array nums, return the length of the longest strictly increasing subsequence.

                                                                                                                                                                                        +

                                                                                                                                                                                        A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].

                                                                                                                                                                                        +

                                                                                                                                                                                        Example 1:

                                                                                                                                                                                        +
                                                                                                                                                                                        Input: nums = [10,9,2,5,3,7,101,18]
                                                                                                                                                                                        +Output: 4
                                                                                                                                                                                        +Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
                                                                                                                                                                                        +

                                                                                                                                                                                        Example 2:

                                                                                                                                                                                        +
                                                                                                                                                                                        Input: nums = [0,1,0,3,2,3]
                                                                                                                                                                                        +Output: 4
                                                                                                                                                                                        +

                                                                                                                                                                                        Example 3:

                                                                                                                                                                                        +
                                                                                                                                                                                        Input: nums = [7,7,7,7,7,7,7]
                                                                                                                                                                                        +Output: 1
                                                                                                                                                                                        +

                                                                                                                                                                                        Constraints:

                                                                                                                                                                                        +
                                                                                                                                                                                          +
                                                                                                                                                                                        • 1 <= nums.length <= 2500
                                                                                                                                                                                        • +
                                                                                                                                                                                        • -104 <= nums[i] <= 104
                                                                                                                                                                                        • +
                                                                                                                                                                                        +

                                                                                                                                                                                        Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

                                                                                                                                                                                        +

                                                                                                                                                                                        題目大意

                                                                                                                                                                                        +

                                                                                                                                                                                        給你一個整事的數組 nums, 找到其中最長遞增子序列的長度

                                                                                                                                                                                        +
                                                                                                                                                                                          +
                                                                                                                                                                                        • 子序列不一定是連續的
                                                                                                                                                                                        • +
                                                                                                                                                                                        • 子串一定是連續的
                                                                                                                                                                                        • +
                                                                                                                                                                                        +

                                                                                                                                                                                        解題思路

                                                                                                                                                                                        +

                                                                                                                                                                                        方法一: DP

                                                                                                                                                                                        +

                                                                                                                                                                                        dp[i]表示nums[i]這個數結尾的最長遞增子序列的長度 +譬如要找dp[5]的直, 也就是球nums[5]為結尾的最長遞增子序列 +只要找到結尾比nums[5]小的子序列, 然後把 nums[5]接到最後, +就可以形成新的遞增子序列, 而這個新子序列長度+1

                                                                                                                                                                                        +

                                                                                                                                                                                        方法二: DP + 二分搜尋

                                                                                                                                                                                        +

                                                                                                                                                                                        patience sorting (耐心排序) +給一組 [6, 3 ,5 ,10, 11, 2, 9, 14, 13, 7, 4, 8, 12] +只能把數字小的放在數字大的堆上, +如果當前數字太大沒有可以放置的堆, 則新建一個堆, +如果當前排有很多堆可以選擇, 則選擇最左邊的那一堆放, 因為這樣可以確保堆頂是有序的(2,4,7,8,12) +6 5 10 11 14 +3 4 9 8 13 +2 7 12

                                                                                                                                                                                        +

                                                                                                                                                                                        堆數就是最長遞增子序列的長度 +[3,5,7,8,12]

                                                                                                                                                                                        +

                                                                                                                                                                                        來源

                                                                                                                                                                                        + +

                                                                                                                                                                                        解答

                                                                                                                                                                                        +

                                                                                                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0300.Longest-Increasing-Subsequence/main.go

                                                                                                                                                                                        +
                                                                                                                                                                                        package longestincreasingsubsequence
                                                                                                                                                                                        +
                                                                                                                                                                                        +import "fmt"
                                                                                                                                                                                        +
                                                                                                                                                                                        +func max(a, b int) int {
                                                                                                                                                                                        +    if a > b {
                                                                                                                                                                                        +        return a
                                                                                                                                                                                        +    }
                                                                                                                                                                                        +    return b
                                                                                                                                                                                        +}
                                                                                                                                                                                        +
                                                                                                                                                                                        +// DP 解法 O(n^2)
                                                                                                                                                                                        +func LengthOfLIS(nums []int) int {
                                                                                                                                                                                        +    dp := make([]int, len(nums))
                                                                                                                                                                                        +    for idx := 0; idx < len(dp); idx++ {
                                                                                                                                                                                        +        dp[idx] = 1
                                                                                                                                                                                        +    }
                                                                                                                                                                                        +
                                                                                                                                                                                        +    res := 0
                                                                                                                                                                                        +    for i := 0; i < len(nums); i++ {
                                                                                                                                                                                        +        for j := 0; j < i; j++ {
                                                                                                                                                                                        +            if nums[i] > nums[j] {
                                                                                                                                                                                        +                // 找到下一個數值比現在的大
                                                                                                                                                                                        +                dp[i] = max(dp[i], dp[j]+1)
                                                                                                                                                                                        +            }
                                                                                                                                                                                        +        }
                                                                                                                                                                                        +        res = max(res, dp[i])
                                                                                                                                                                                        +    }
                                                                                                                                                                                        +    // fmt.Println(dp)
                                                                                                                                                                                        +    return res
                                                                                                                                                                                        +}
                                                                                                                                                                                        +
                                                                                                                                                                                        +func LengthOfLIS2(nums []int) int {
                                                                                                                                                                                        +    dp := make([]int, len(nums)+1)
                                                                                                                                                                                        +    dp[0] = 0
                                                                                                                                                                                        +    res := 0
                                                                                                                                                                                        +
                                                                                                                                                                                        +    for i := 1; i <= len(nums);="" i++="" {="" for="" j="" :="1;" <="" i;="" j++="" if="" nums[i-1]=""> nums[j-1] {
                                                                                                                                                                                        +                // 找到前面比現在結尾還小的子序列
                                                                                                                                                                                        +                dp[i] = max(dp[i], dp[j])
                                                                                                                                                                                        +            }
                                                                                                                                                                                        +        }
                                                                                                                                                                                        +        dp[i] = dp[i] + 1
                                                                                                                                                                                        +        res = max(res, dp[i])
                                                                                                                                                                                        +    }
                                                                                                                                                                                        +    // fmt.Println(dp)
                                                                                                                                                                                        +    return res
                                                                                                                                                                                        +}
                                                                                                                                                                                        +
                                                                                                                                                                                        +// DP + 二分搜尋:patience sorting. O(nlogn)
                                                                                                                                                                                        +func LengthOfLISPatience(nums []int) int {
                                                                                                                                                                                        +    top := make([]int, len(nums))
                                                                                                                                                                                        +
                                                                                                                                                                                        +    // 牌堆數初始化為0
                                                                                                                                                                                        +    piles := 0
                                                                                                                                                                                        +
                                                                                                                                                                                        +    for i := 0; i < len(nums); i++ {
                                                                                                                                                                                        +        poker := nums[i]
                                                                                                                                                                                        +
                                                                                                                                                                                        +        // 搜尋左側邊界的二元搜尋
                                                                                                                                                                                        +        left, right := 0, piles
                                                                                                                                                                                        +        // fmt.Printf("i:%d\tL:%d\tR:%d\n", i, left, right)
                                                                                                                                                                                        +        for left < right {
                                                                                                                                                                                        +            mid := left + (right-left)/2
                                                                                                                                                                                        +            if top[mid] > poker {
                                                                                                                                                                                        +                // 現在的牌比堆小, 縮小範圍
                                                                                                                                                                                        +                right = mid
                                                                                                                                                                                        +            } else if top[mid] < poker {
                                                                                                                                                                                        +                // 現在的牌比堆大
                                                                                                                                                                                        +                left = mid + 1
                                                                                                                                                                                        +            } else {
                                                                                                                                                                                        +                right = mid
                                                                                                                                                                                        +            }
                                                                                                                                                                                        +        }
                                                                                                                                                                                        +
                                                                                                                                                                                        +        // 沒有找到堆, 建立一個新的堆
                                                                                                                                                                                        +        if left == piles {
                                                                                                                                                                                        +            piles++
                                                                                                                                                                                        +        }
                                                                                                                                                                                        +        // 再把這張牌放在堆的頂端
                                                                                                                                                                                        +        top[left] = poker
                                                                                                                                                                                        +    }
                                                                                                                                                                                        +    fmt.Println(top)
                                                                                                                                                                                        +    return piles
                                                                                                                                                                                        +}
                                                                                                                                                                                        +
                                                                                                                                                                                        +
                                                                                                                                                                                        go test -benchmem -run=none LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence -bench=.
                                                                                                                                                                                        +goos: darwin
                                                                                                                                                                                        +goarch: amd64
                                                                                                                                                                                        +pkg: LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence
                                                                                                                                                                                        +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                        +BenchmarkLengthOfLIS-8                  18300901                64.77 ns/op           64 B/op          1 allocs/op
                                                                                                                                                                                        +BenchmarkLengthOfLIS2-8                 17410562                68.98 ns/op           80 B/op          1 allocs/op
                                                                                                                                                                                        +BenchmarkLengthOfLISPatience-8          20768851                58.47 ns/op           64 B/op          1 allocs/op
                                                                                                                                                                                        +PASS
                                                                                                                                                                                        +ok      LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence      3.812s
                                                                                                                                                                                        +
                                                                                                                                                                                        +
                                                                                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                        + +
                                                                                                                                                                                        + +
                                                                                                                                                                                        +
                                                                                                                                                                                        +
                                                                                                                                                                                        + +

                                                                                                                                                                                        results matching ""

                                                                                                                                                                                        +
                                                                                                                                                                                          + +
                                                                                                                                                                                          +
                                                                                                                                                                                          + +

                                                                                                                                                                                          No results matching ""

                                                                                                                                                                                          + +
                                                                                                                                                                                          +
                                                                                                                                                                                          +
                                                                                                                                                                                          + +
                                                                                                                                                                                          +
                                                                                                                                                                                          + +
                                                                                                                                                                                          + + + + + + +
                                                                                                                                                                                          + + +
                                                                                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0300.Longest-Increasing-Subsequence/main.go b/Leetcode/0300.Longest-Increasing-Subsequence/main.go new file mode 100644 index 000000000..97300191c --- /dev/null +++ b/Leetcode/0300.Longest-Increasing-Subsequence/main.go @@ -0,0 +1,84 @@ +package longestincreasingsubsequence + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +// DP ่งฃๆณ• O(n^2) +func LengthOfLIS(nums []int) int { + dp := make([]int, len(nums)) + for idx := 0; idx < len(dp); idx++ { + dp[idx] = 1 + } + + res := 0 + for i := 0; i < len(nums); i++ { + for j := 0; j < i; j++ { + if nums[i] > nums[j] { + // ๆ‰พๅˆฐไธ‹ไธ€ๅ€‹ๆ•ธๅ€ผๆฏ”็พๅœจ็š„ๅคง + dp[i] = max(dp[i], dp[j]+1) + } + } + res = max(res, dp[i]) + } + // fmt.Println(dp) + return res +} + +func LengthOfLIS2(nums []int) int { + dp := make([]int, len(nums)+1) + dp[0] = 0 + res := 0 + + for i := 1; i <= len(nums); i++ { + for j := 1; j < i; j++ { + if nums[i-1] > nums[j-1] { + // ๆ‰พๅˆฐๅ‰้ขๆฏ”็พๅœจ็ตๅฐพ้‚„ๅฐ็š„ๅญๅบๅˆ— + dp[i] = max(dp[i], dp[j]) + } + } + dp[i] = dp[i] + 1 + res = max(res, dp[i]) + } + // fmt.Println(dp) + return res +} + +// DP + ไบŒๅˆ†ๆœๅฐ‹:patience sorting. O(nlogn) +func LengthOfLISPatience(nums []int) int { + top := make([]int, len(nums)) + + // ็‰Œๅ †ๆ•ธๅˆๅง‹ๅŒ–็‚บ0 + piles := 0 + + for i := 0; i < len(nums); i++ { + poker := nums[i] + + // ๆœๅฐ‹ๅทฆๅด้‚Š็•Œ็š„ไบŒๅ…ƒๆœๅฐ‹ + left, right := 0, piles + // fmt.Printf("i:%d\tL:%d\tR:%d\n", i, left, right) + for left < right { + mid := left + (right-left)/2 + if top[mid] > poker { + // ็พๅœจ็š„็‰Œๆฏ”ๅ †ๅฐ, ็ธฎๅฐ็ฏ„ๅœ + right = mid + } else if top[mid] < poker { + // ็พๅœจ็š„็‰Œๆฏ”ๅ †ๅคง + left = mid + 1 + } else { + right = mid + } + } + + // ๆฒ’ๆœ‰ๆ‰พๅˆฐๅ †, ๅปบ็ซ‹ไธ€ๅ€‹ๆ–ฐ็š„ๅ † + if left == piles { + piles++ + } + // ๅ†ๆŠŠ้€™ๅผต็‰Œๆ”พๅœจๅ †็š„้ ‚็ซฏ + top[left] = poker + } + return piles +} diff --git a/Leetcode/0300.Longest-Increasing-Subsequence/main_test.go b/Leetcode/0300.Longest-Increasing-Subsequence/main_test.go new file mode 100644 index 000000000..9af0c3dd9 --- /dev/null +++ b/Leetcode/0300.Longest-Increasing-Subsequence/main_test.go @@ -0,0 +1,81 @@ +package longestincreasingsubsequence + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{10, 9, 2, 5, 3, 7, 101, 18}, + 4, + }, + { + []int{0, 1, 0, 3, 2, 3}, + 4, + }, + { + []int{7, 7, 7, 7, 7, 7, 7}, + 1, + }, + { + []int{6, 3, 5, 10, 11, 2, 9, 14, 13, 7, 4, 8, 12}, + 5, + }, +} + +func TestLengthOfLIS(t *testing.T) { + for _, tt := range tests { + if got := LengthOfLIS(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestLengthOfLIS2(t *testing.T) { + for _, tt := range tests { + if got := LengthOfLIS2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestLengthOfLISPatience(t *testing.T) { + for _, tt := range tests { + if got := LengthOfLISPatience(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLengthOfLIS(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LengthOfLIS(tests[0].arg1) + } +} +func BenchmarkLengthOfLIS2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LengthOfLIS2(tests[0].arg1) + } +} +func BenchmarkLengthOfLISPatience(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LengthOfLISPatience(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkLengthOfLIS-8 18300901 64.77 ns/op 64 B/op 1 allocs/op +BenchmarkLengthOfLIS2-8 17410562 68.98 ns/op 80 B/op 1 allocs/op +BenchmarkLengthOfLISPatience-8 20768851 58.47 ns/op 64 B/op 1 allocs/op +PASS +ok LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence 3.812s +*/ diff --git a/Leetcode/0310.Minimum-Height-Trees/index.html b/Leetcode/0310.Minimum-Height-Trees/index.html new file mode 100644 index 000000000..0e27dfa52 --- /dev/null +++ b/Leetcode/0310.Minimum-Height-Trees/index.html @@ -0,0 +1,3895 @@ + + + + + + + 0310.Minimum Height Trees ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                          +
                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                          + +
                                                                                                                                                                                          + +
                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                          +
                                                                                                                                                                                          + +
                                                                                                                                                                                          +
                                                                                                                                                                                          + +
                                                                                                                                                                                          + +

                                                                                                                                                                                          310. Minimum Height Trees

                                                                                                                                                                                          題目

                                                                                                                                                                                          +

                                                                                                                                                                                          A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

                                                                                                                                                                                          +

                                                                                                                                                                                          Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).

                                                                                                                                                                                          +

                                                                                                                                                                                          Return a list of all MHTs' root labels. You can return the answer in any order.

                                                                                                                                                                                          +

                                                                                                                                                                                          The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

                                                                                                                                                                                          +

                                                                                                                                                                                          Example 1: +

                                                                                                                                                                                          +
                                                                                                                                                                                          Input: n = 4, edges = [[1,0],[1,2],[1,3]]
                                                                                                                                                                                          +Output: [1]
                                                                                                                                                                                          +Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT.
                                                                                                                                                                                          +

                                                                                                                                                                                          Example 2: +

                                                                                                                                                                                          +
                                                                                                                                                                                          Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
                                                                                                                                                                                          +Output: [3,4]
                                                                                                                                                                                          +

                                                                                                                                                                                          Constraints:

                                                                                                                                                                                          +
                                                                                                                                                                                            +
                                                                                                                                                                                          • 1 <= n <= 2 * 104
                                                                                                                                                                                          • +
                                                                                                                                                                                          • edges.length == n - 1
                                                                                                                                                                                          • +
                                                                                                                                                                                          • 0 <= ai, bi < n
                                                                                                                                                                                          • +
                                                                                                                                                                                          • ai != bi
                                                                                                                                                                                          • +
                                                                                                                                                                                          • All the pairs (ai, bi) are distinct.
                                                                                                                                                                                          • +
                                                                                                                                                                                          • The given input is guaranteed to be a tree and there will be no repeated edges.
                                                                                                                                                                                          • +
                                                                                                                                                                                          +

                                                                                                                                                                                          題目大意

                                                                                                                                                                                          +

                                                                                                                                                                                          輸入一個n個節點的二叉樹, 計算出最小高度(root到left的最短距離)

                                                                                                                                                                                          +

                                                                                                                                                                                          解題思路

                                                                                                                                                                                          +

                                                                                                                                                                                          用BFS來解. Queue +起點就是root, 終點就是最靠近root的那個葉節點(就是兩個子節點都是null)

                                                                                                                                                                                          +

                                                                                                                                                                                          來源

                                                                                                                                                                                          + +

                                                                                                                                                                                          解答

                                                                                                                                                                                          +

                                                                                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0310.Minimum-Height-Trees/main.go

                                                                                                                                                                                          +
                                                                                                                                                                                          package minimumheighttrees
                                                                                                                                                                                          +
                                                                                                                                                                                          +import "fmt"
                                                                                                                                                                                          +
                                                                                                                                                                                          +func FindMinHeightTrees(n int, edges [][]int) []int {
                                                                                                                                                                                          +    if n == 1 {
                                                                                                                                                                                          +        return []int{0}
                                                                                                                                                                                          +    }
                                                                                                                                                                                          +
                                                                                                                                                                                          +    graph := make(map[int][]int)
                                                                                                                                                                                          +    degree := make(map[int]int, n) //出度: 出度是指從該節點(頂點)出發的邊的條數
                                                                                                                                                                                          +    // 建立對應關係
                                                                                                                                                                                          +    for _, v := range edges {
                                                                                                                                                                                          +        if _, ok := graph[v[0]]; ok {
                                                                                                                                                                                          +            graph[v[0]] = append(graph[v[0]], v[1])
                                                                                                                                                                                          +        } else {
                                                                                                                                                                                          +            // 沒找到
                                                                                                                                                                                          +            graph[v[0]] = []int{v[1]}
                                                                                                                                                                                          +        }
                                                                                                                                                                                          +
                                                                                                                                                                                          +        if _, ok := graph[v[1]]; ok {
                                                                                                                                                                                          +            graph[v[1]] = append(graph[v[1]], v[0])
                                                                                                                                                                                          +        } else {
                                                                                                                                                                                          +            // 沒找到
                                                                                                                                                                                          +            graph[v[1]] = []int{v[0]}
                                                                                                                                                                                          +        }
                                                                                                                                                                                          +        degree[v[0]]++
                                                                                                                                                                                          +        degree[v[1]]++
                                                                                                                                                                                          +    }
                                                                                                                                                                                          +    fmt.Printf("graph: %+v \n", graph)
                                                                                                                                                                                          +    fmt.Printf("degree: %+v \n", degree)
                                                                                                                                                                                          +
                                                                                                                                                                                          +    var queue []int
                                                                                                                                                                                          +    for key, value := range degree { //先找到出度為1的點, 加到Queue
                                                                                                                                                                                          +        if value == 1 {
                                                                                                                                                                                          +            queue = append(queue, key)
                                                                                                                                                                                          +        }
                                                                                                                                                                                          +    }
                                                                                                                                                                                          +    fmt.Printf("queue: %+v \n", queue)
                                                                                                                                                                                          +
                                                                                                                                                                                          +    leaves := []int{}
                                                                                                                                                                                          +    for len(queue) != 0 {
                                                                                                                                                                                          +        leaves = leaves[0:0]
                                                                                                                                                                                          +        size := len(queue)
                                                                                                                                                                                          +
                                                                                                                                                                                          +        for i := 0; i < size; i++ {
                                                                                                                                                                                          +            leaves = append(leaves, queue[i])
                                                                                                                                                                                          +            for _, neighbor := range graph[queue[i]] { // 將該點鄰接出度-1, 等於1時加入Queue
                                                                                                                                                                                          +                degree[neighbor]--
                                                                                                                                                                                          +                if degree[neighbor] == 1 {
                                                                                                                                                                                          +                    queue = append(queue, neighbor)
                                                                                                                                                                                          +                }
                                                                                                                                                                                          +            }
                                                                                                                                                                                          +        }
                                                                                                                                                                                          +        queue = queue[size:]
                                                                                                                                                                                          +    }
                                                                                                                                                                                          +    return leaves
                                                                                                                                                                                          +}
                                                                                                                                                                                          +
                                                                                                                                                                                          +/*
                                                                                                                                                                                          +n: 4,    edges: [][]int{{1, 0}, {1, 2}, {1, 3}},
                                                                                                                                                                                          +graph: map[0:[1] 1:[0 2 3] 2:[1] 3:[1]]
                                                                                                                                                                                          +           0 (degree: 1)
                                                                                                                                                                                          +          /
                                                                                                                                                                                          +         1 (3)
                                                                                                                                                                                          +        / \
                                                                                                                                                                                          +    2(1)   3(1)
                                                                                                                                                                                          +
                                                                                                                                                                                          +degree: map[0:1 1:3 2:1 3:1]
                                                                                                                                                                                          +queue: [2 3 0] (先degree=1)
                                                                                                                                                                                          +*/
                                                                                                                                                                                          +
                                                                                                                                                                                          +
                                                                                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                          + +
                                                                                                                                                                                          + +
                                                                                                                                                                                          +
                                                                                                                                                                                          +
                                                                                                                                                                                          + +

                                                                                                                                                                                          results matching ""

                                                                                                                                                                                          +
                                                                                                                                                                                            + +
                                                                                                                                                                                            +
                                                                                                                                                                                            + +

                                                                                                                                                                                            No results matching ""

                                                                                                                                                                                            + +
                                                                                                                                                                                            +
                                                                                                                                                                                            +
                                                                                                                                                                                            + +
                                                                                                                                                                                            +
                                                                                                                                                                                            + +
                                                                                                                                                                                            + + + + + + +
                                                                                                                                                                                            + + +
                                                                                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0310.Minimum-Height-Trees/main.go b/Leetcode/0310.Minimum-Height-Trees/main.go new file mode 100644 index 000000000..516de5d4d --- /dev/null +++ b/Leetcode/0310.Minimum-Height-Trees/main.go @@ -0,0 +1,71 @@ +package minimumheighttrees + +import "fmt" + +func FindMinHeightTrees(n int, edges [][]int) []int { + if n == 1 { + return []int{0} + } + + graph := make(map[int][]int) + degree := make(map[int]int, n) //ๅ‡บๅบฆ: ๅ‡บๅบฆๆ˜ฏๆŒ‡ๅพž่ฉฒ็ฏ€้ปž๏ผˆ้ ‚้ปž๏ผ‰ๅ‡บ็™ผ็š„้‚Š็š„ๆขๆ•ธ + // ๅปบ็ซ‹ๅฐๆ‡‰้—œไฟ‚ + for _, v := range edges { + if _, ok := graph[v[0]]; ok { + graph[v[0]] = append(graph[v[0]], v[1]) + } else { + // ๆฒ’ๆ‰พๅˆฐ + graph[v[0]] = []int{v[1]} + } + + if _, ok := graph[v[1]]; ok { + graph[v[1]] = append(graph[v[1]], v[0]) + } else { + // ๆฒ’ๆ‰พๅˆฐ + graph[v[1]] = []int{v[0]} + } + degree[v[0]]++ + degree[v[1]]++ + } + fmt.Printf("graph: %+v \n", graph) + fmt.Printf("degree: %+v \n", degree) + + var queue []int + for key, value := range degree { //ๅ…ˆๆ‰พๅˆฐๅ‡บๅบฆ็‚บ1็š„้ปž, ๅŠ ๅˆฐQueue + if value == 1 { + queue = append(queue, key) + } + } + fmt.Printf("queue: %+v \n", queue) + + leaves := []int{} + for len(queue) != 0 { + leaves = leaves[0:0] + size := len(queue) + + for i := 0; i < size; i++ { + leaves = append(leaves, queue[i]) + for _, neighbor := range graph[queue[i]] { // ๅฐ‡่ฉฒ้ปž้„ฐๆŽฅๅ‡บๅบฆ-1, ็ญ‰ๆ–ผ1ๆ™‚ๅŠ ๅ…ฅQueue + degree[neighbor]-- + if degree[neighbor] == 1 { + queue = append(queue, neighbor) + } + } + } + queue = queue[size:] + } + return leaves +} + +/* +n: 4, edges: [][]int{{1, 0}, {1, 2}, {1, 3}}, +graph: map[0:[1] 1:[0 2 3] 2:[1] 3:[1]] + 0 (degree: 1) + / + 1 (3) + / \ + 2(1) 3(1) + +degree: map[0:1 1:3 2:1 3:1] +queue: [2 3 0] (ๅ…ˆdegree=1) +*/ diff --git a/Leetcode/0310.Minimum-Height-Trees/main_test.go b/Leetcode/0310.Minimum-Height-Trees/main_test.go new file mode 100644 index 000000000..75b77dc45 --- /dev/null +++ b/Leetcode/0310.Minimum-Height-Trees/main_test.go @@ -0,0 +1,31 @@ +package minimumheighttrees + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 int + arg2 [][]int + want []int +}{ + { + 4, + [][]int{{1, 0}, {1, 2}, {1, 3}}, + []int{1}, + }, + { + 6, + [][]int{{3, 0}, {3, 1}, {3, 2}, {3, 4}, {5, 4}}, + []int{3, 4}, + }, +} + +func TestFindMinHeightTrees(t *testing.T) { + for _, tt := range tests { + if got := FindMinHeightTrees(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} diff --git a/Leetcode/0322.Coin-Change/Coin-Change.go b/Leetcode/0322.Coin-Change/Coin-Change.go new file mode 100644 index 000000000..4ac4f3a9f --- /dev/null +++ b/Leetcode/0322.Coin-Change/Coin-Change.go @@ -0,0 +1,104 @@ +package coinchange + +import ( + "math" +) + +func min(a, b int) int { + if a > b { + return b + } + return a +} + +var memo = map[int]int{} + +func dp(coins []int, n int) int { + // ๆŸฅ่ฉขๅ‚™ๅฟ˜้Œ„ ้ฟๅ…้‡่ค‡ + if _, vok := memo[n]; vok { + return memo[n] + } + + if n == 0 { + return 0 + } + + if n < 0 { + return -1 + } + + res := math.MaxInt + for _, coin := range coins { + subproblem := dp(coins, n-coin) + if subproblem == -1 { + continue + } + res = min(res, 1+subproblem) + } + if res != math.MaxInt { + memo[n] = res + } else { + memo[n] = -1 + } + return memo[n] +} + +// ๅ‚™ๅฟ˜้Œ„ ้ž่ฟด ๆ™‚้–“่ค‡้›œO(kn). +func CoinChangeMemoryTableRecursion(coins []int, amount int) int { + memo = map[int]int{} + return dp(coins, amount) +} + +// dp array ่ฟญไปฃ่งฃๆณ• +func CoinChangeDP(coins []int, amount int) int { + dp := make([]int, amount+1) + dp[0] = 0 + + // ๅˆๅง‹ๅŒ–, ๆนŠๆˆ amount ้‡‘้ก็š„็กฌๅนฃ ๆœ€ๅคšๅฐฑ amount ๅ€‹(ๅ…จ้ƒฝ็”จ1ๅ…ƒ), ๆ‰€ไปฅ amount+1็›ธ็•ถๆ–ผๆญฃ็š„็„ก็ชฎ + // dp[]็š„ๅฎš็พฉ: ็•ถ็›ฎๆจ™้‡‘้ก็‚บiๆ™‚, ่‡ณๅฐ‘้œ€่ฆdp[i]ๆžš็กฌๅนฃๆนŠๅ‡บ + for i := 1; i < len(dp); i++ { + dp[i] = amount + 1 + } + + // ๅค–ๅฑค for ๅพช็’ฐ้ๆญทๆ‰€ๆœ‰็‹€ๆ…‹็š„ๆ‰€ๆœ‰ๅ–ๅ€ผ + for i := 1; i <= amount; i++ { + // ๅ…งๅฑค for ๅพช็’ฐ้ๆญท็ƒๆ‰€ๆœ‰้ธๆ“‡็š„ๆœ€ๅฐๅ€ผ + for _, coin := range coins { + if i-coin < 0 { + continue + } + dp[i] = min(dp[i], 1+dp[i-coin]) + } + } + if dp[amount] > amount { + return -1 + } + + return dp[amount] +} + +func CoinChange(coins []int, n int) int { + var dpClosure func(n int) int + dpClosure = func(n int) int { + if n == 0 { + return 0 + } + if n < 0 { + return -1 + } + res := math.MaxInt + for _, coin := range coins { + subproblem := dpClosure(n - coin) + if subproblem == -1 { + continue + } + res = min(res, 1+subproblem) + } + if res != math.MaxInt { + return res + } else { + return -1 + } + } + return dpClosure(n) +} diff --git a/Leetcode/0322.Coin-Change/Coin-Change_test.go b/Leetcode/0322.Coin-Change/Coin-Change_test.go new file mode 100644 index 000000000..60a48336e --- /dev/null +++ b/Leetcode/0322.Coin-Change/Coin-Change_test.go @@ -0,0 +1,88 @@ +package coinchange + +import ( + "testing" +) + +var tests = []struct { + arg1 []int + arg2 int + want int +}{ + { + []int{1, 2, 5}, + 11, + 3, + }, + { + []int{2}, + 3, + -1, + }, + { + []int{1}, + 0, + 0, + }, +} + +func TestCoinChange(t *testing.T) { + for _, tt := range tests { + if got := CoinChange(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestCoinChangeDP(t *testing.T) { + for _, tt := range tests { + if got := CoinChangeDP(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestCoinChangeMemoryTableRecursion(t *testing.T) { + for _, tt := range tests { + if got := CoinChangeMemoryTableRecursion(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +var arg1 = []int{1, 2, 5} +var arg2 = 11 + +func BenchmarkCoinChange(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + CoinChange(arg1, arg2) + } +} + +func BenchmarkCoinChangeDP(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + CoinChangeDP(arg1, arg2) + } +} + +func BenchmarkCoinChangeMemoryTableRecursion(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + CoinChangeMemoryTableRecursion(arg1, arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0322.Coin-Change -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0322.Coin-Change +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkCoinChange-8 323095 4531 ns/op 0 B/op 0 allocs/op +BenchmarkCoinChangeDP-8 12356360 90.89 ns/op 96 B/op 1 allocs/op +BenchmarkCoinChangeMemoryTableRecursion-8 1238718 955.2 ns/op 493 B/op 3 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0322.Coin-Change 5.708s +*/ diff --git a/Leetcode/0322.Coin-Change/index.html b/Leetcode/0322.Coin-Change/index.html new file mode 100644 index 000000000..d4905c981 --- /dev/null +++ b/Leetcode/0322.Coin-Change/index.html @@ -0,0 +1,3933 @@ + + + + + + + 0322.Coin Change ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                            +
                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                            + +
                                                                                                                                                                                            + +
                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                            +
                                                                                                                                                                                            + +
                                                                                                                                                                                            +
                                                                                                                                                                                            + +
                                                                                                                                                                                            + +

                                                                                                                                                                                            322. Coin Change

                                                                                                                                                                                            題目

                                                                                                                                                                                            +

                                                                                                                                                                                            You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

                                                                                                                                                                                            +

                                                                                                                                                                                            Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

                                                                                                                                                                                            +

                                                                                                                                                                                            You may assume that you have an infinite number of each kind of coin.

                                                                                                                                                                                            +

                                                                                                                                                                                            Example 1:

                                                                                                                                                                                            +

                                                                                                                                                                                            Input: coins = [1,2,5], amount = 11 +Output: 3 +Explanation: 11 = 5 + 5 + 1 +Example 2:

                                                                                                                                                                                            +

                                                                                                                                                                                            Input: coins = [2], amount = 3 +Output: -1 +Example 3:

                                                                                                                                                                                            +

                                                                                                                                                                                            Input: coins = [1], amount = 0 +Output: 0

                                                                                                                                                                                            +

                                                                                                                                                                                            Constraints:

                                                                                                                                                                                            +

                                                                                                                                                                                            1 <= coins.length <= 12 +1 <= coins[i] <= 231 - 1 +0 <= amount <= 104

                                                                                                                                                                                            +

                                                                                                                                                                                            題目大意

                                                                                                                                                                                            +

                                                                                                                                                                                            給妳 k 種面值的硬幣, 面值分別為 c1,c2 ...,ck, 每種硬幣的數量無限. +再給你一個總金額. 求出最少 需要幾枚硬幣湊出這個金額, 如果不能湊出 return -1.

                                                                                                                                                                                            +

                                                                                                                                                                                            解題思路

                                                                                                                                                                                            +

                                                                                                                                                                                            dp(n) 的定義: 輸入一個目標金額n, 返回湊出目標金額n的最少硬幣數量

                                                                                                                                                                                            +

                                                                                                                                                                                            來源

                                                                                                                                                                                            + +

                                                                                                                                                                                            解答

                                                                                                                                                                                            +

                                                                                                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0322.Coin-Change/Coin-Change.go

                                                                                                                                                                                            +
                                                                                                                                                                                            package coinchange
                                                                                                                                                                                            +
                                                                                                                                                                                            +import (
                                                                                                                                                                                            +    "math"
                                                                                                                                                                                            +)
                                                                                                                                                                                            +
                                                                                                                                                                                            +func min(a, b int) int {
                                                                                                                                                                                            +    if a > b {
                                                                                                                                                                                            +        return b
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +    return a
                                                                                                                                                                                            +}
                                                                                                                                                                                            +
                                                                                                                                                                                            +var memo = map[int]int{}
                                                                                                                                                                                            +
                                                                                                                                                                                            +func dp(coins []int, n int) int {
                                                                                                                                                                                            +    // 查詢備忘錄 避免重複
                                                                                                                                                                                            +    if _, vok := memo[n]; vok {
                                                                                                                                                                                            +        return memo[n]
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +
                                                                                                                                                                                            +    if n == 0 {
                                                                                                                                                                                            +        return 0
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +
                                                                                                                                                                                            +    if n < 0 {
                                                                                                                                                                                            +        return -1
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +
                                                                                                                                                                                            +    res := math.MaxInt
                                                                                                                                                                                            +    for _, coin := range coins {
                                                                                                                                                                                            +        subproblem := dp(coins, n-coin)
                                                                                                                                                                                            +        if subproblem == -1 {
                                                                                                                                                                                            +            continue
                                                                                                                                                                                            +        }
                                                                                                                                                                                            +        res = min(res, 1+subproblem)
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +    if res != math.MaxInt {
                                                                                                                                                                                            +        memo[n] = res
                                                                                                                                                                                            +    } else {
                                                                                                                                                                                            +        memo[n] = -1
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +    return memo[n]
                                                                                                                                                                                            +}
                                                                                                                                                                                            +
                                                                                                                                                                                            +// 備忘錄 遞迴 時間複雜O(kn).
                                                                                                                                                                                            +func CoinChangeMemoryTableRecursion(coins []int, amount int) int {
                                                                                                                                                                                            +    return dp(coins, amount)
                                                                                                                                                                                            +}
                                                                                                                                                                                            +
                                                                                                                                                                                            +// dp array 迭代解法
                                                                                                                                                                                            +func CoinChangeDP(coins []int, amount int) int {
                                                                                                                                                                                            +    dp := make([]int, amount+1)
                                                                                                                                                                                            +    dp[0] = 0
                                                                                                                                                                                            +
                                                                                                                                                                                            +    // 初始化, 湊成 amount 金額的硬幣 最多就 amount 個(全都用1元), 所以 amount+1相當於正的無窮
                                                                                                                                                                                            +    // dp[]的定義: 當目標金額為i時, 至少需要dp[i]枚硬幣湊出
                                                                                                                                                                                            +    for i := 1; i < len(dp); i++ {
                                                                                                                                                                                            +        dp[i] = amount + 1
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +
                                                                                                                                                                                            +    // 外層 for 循環遍歷所有狀態的所有取值
                                                                                                                                                                                            +    for i := 1; i <= 0="" amount;="" i++="" {="" ๅ…งๅฑค="" for="" ๅพช็’ฐ้ๆญท็ƒๆ‰€ๆœ‰้ธๆ“‡็š„ๆœ€ๅฐๅ€ผ="" _,="" coin="" :="range" coins="" if="" i-coin="" <="" continue="" }="" dp[i]="min(dp[i]," 1+dp[i-coin])="" dp[amount]=""> amount {
                                                                                                                                                                                            +        return -1
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +
                                                                                                                                                                                            +    return dp[amount]
                                                                                                                                                                                            +}
                                                                                                                                                                                            +
                                                                                                                                                                                            +func CoinChange(coins []int, n int) int {
                                                                                                                                                                                            +    var dpClosure func(n int) int
                                                                                                                                                                                            +    dpClosure = func(n int) int {
                                                                                                                                                                                            +        if n == 0 {
                                                                                                                                                                                            +            return 0
                                                                                                                                                                                            +        }
                                                                                                                                                                                            +        if n < 0 {
                                                                                                                                                                                            +            return -1
                                                                                                                                                                                            +        }
                                                                                                                                                                                            +        res := math.MaxInt
                                                                                                                                                                                            +        for _, coin := range coins {
                                                                                                                                                                                            +            subproblem := dpClosure(n - coin)
                                                                                                                                                                                            +            if subproblem == -1 {
                                                                                                                                                                                            +                continue
                                                                                                                                                                                            +            }
                                                                                                                                                                                            +            res = min(res, 1+subproblem)
                                                                                                                                                                                            +        }
                                                                                                                                                                                            +        if res != math.MaxInt {
                                                                                                                                                                                            +            return res
                                                                                                                                                                                            +        } else {
                                                                                                                                                                                            +            return -1
                                                                                                                                                                                            +        }
                                                                                                                                                                                            +    }
                                                                                                                                                                                            +    return dpClosure(n)
                                                                                                                                                                                            +}
                                                                                                                                                                                            +
                                                                                                                                                                                            +
                                                                                                                                                                                            go test -benchmem -run=none LeetcodeGolang/Leetcode/0322.Coin-Change -bench=.
                                                                                                                                                                                            +goos: darwin
                                                                                                                                                                                            +goarch: amd64
                                                                                                                                                                                            +pkg: LeetcodeGolang/Leetcode/0322.Coin-Change
                                                                                                                                                                                            +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
                                                                                                                                                                                            +BenchmarkCoinChange-4                             273376              4452 ns/op               0 B/op          0 allocs/op
                                                                                                                                                                                            +BenchmarkCoinChangeDP-4                         11071686               128.1 ns/op            96 B/op          1 allocs/op
                                                                                                                                                                                            +BenchmarkCoinChangeMemoryTableRecursion-4       57663068                23.69 ns/op            0 B/op          0 allocs/op
                                                                                                                                                                                            +PASS
                                                                                                                                                                                            +ok      LeetcodeGolang/Leetcode/0322.Coin-Change        4.194s
                                                                                                                                                                                            +
                                                                                                                                                                                            +
                                                                                                                                                                                            amount = 11. k=[1,2,5]
                                                                                                                                                                                            +
                                                                                                                                                                                            +amount 0 1 2 3 4 5 ... 9 10 11
                                                                                                                                                                                            +index  0 1 2 3 4 5 ... 9 10 11
                                                                                                                                                                                            +dp     0 1 1 2 2 1 ... 3  2  3
                                                                                                                                                                                            +
                                                                                                                                                                                            +
                                                                                                                                                                                            +dp[5] = 1+min(dp[5-1],dp[5-2],dp[5-5])
                                                                                                                                                                                            +dp[11] = 1+min(dp[10],dp[9],dp[6])
                                                                                                                                                                                            +
                                                                                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                            + +
                                                                                                                                                                                            + +
                                                                                                                                                                                            +
                                                                                                                                                                                            +
                                                                                                                                                                                            + +

                                                                                                                                                                                            results matching ""

                                                                                                                                                                                            +
                                                                                                                                                                                              + +
                                                                                                                                                                                              +
                                                                                                                                                                                              + +

                                                                                                                                                                                              No results matching ""

                                                                                                                                                                                              + +
                                                                                                                                                                                              +
                                                                                                                                                                                              +
                                                                                                                                                                                              + +
                                                                                                                                                                                              +
                                                                                                                                                                                              + +
                                                                                                                                                                                              + + + + + + +
                                                                                                                                                                                              + + +
                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0344.Reverse-String/Reverse-String.go b/Leetcode/0344.Reverse-String/Reverse-String.go new file mode 100644 index 000000000..9ab8364d3 --- /dev/null +++ b/Leetcode/0344.Reverse-String/Reverse-String.go @@ -0,0 +1,7 @@ +package reversestring + +func ReverseString(s []byte) { + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } +} diff --git a/Leetcode/0344.Reverse-String/Reverse-String_test.go b/Leetcode/0344.Reverse-String/Reverse-String_test.go new file mode 100644 index 000000000..f2ce6a7cf --- /dev/null +++ b/Leetcode/0344.Reverse-String/Reverse-String_test.go @@ -0,0 +1,29 @@ +package reversestring + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []byte + want []byte +}{ + { + []byte{'h', 'e', 'l', 'l', 'o'}, + []byte{'o', 'l', 'l', 'e', 'h'}, + }, + { + []byte{'H', 'a', 'n', 'n', 'a', 'h'}, + []byte{'h', 'a', 'n', 'n', 'a', 'H'}, + }, +} + +func TestReverseString(t *testing.T) { + for _, tt := range tests { + ReverseString(tt.arg1) + if !reflect.DeepEqual(tt.arg1, tt.want) { + t.Errorf("got = %v \n want = %v \n", tt.arg1, tt.want) + } + } +} diff --git a/Leetcode/0344.Reverse-String/index.html b/Leetcode/0344.Reverse-String/index.html new file mode 100644 index 000000000..fc23d2eba --- /dev/null +++ b/Leetcode/0344.Reverse-String/index.html @@ -0,0 +1,3819 @@ + + + + + + + 0344.Reverse String ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                              +
                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                              + +
                                                                                                                                                                                              + +
                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                              +
                                                                                                                                                                                              + +
                                                                                                                                                                                              +
                                                                                                                                                                                              + +
                                                                                                                                                                                              + +

                                                                                                                                                                                              344. Reverse String

                                                                                                                                                                                              題目

                                                                                                                                                                                              +

                                                                                                                                                                                              Write a function that reverses a string. The input string is given as an array of characters char[].

                                                                                                                                                                                              +

                                                                                                                                                                                              Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

                                                                                                                                                                                              +

                                                                                                                                                                                              You may assume all the characters consist of printable ascii characters.

                                                                                                                                                                                              +

                                                                                                                                                                                              Example 1:

                                                                                                                                                                                              +
                                                                                                                                                                                              Input: ["h","e","l","l","o"]
                                                                                                                                                                                              +Output: ["o","l","l","e","h"]
                                                                                                                                                                                              +
                                                                                                                                                                                              +

                                                                                                                                                                                              Example 2:

                                                                                                                                                                                              +
                                                                                                                                                                                              Input: ["H","a","n","n","a","h"]
                                                                                                                                                                                              +Output: ["h","a","n","n","a","H"]
                                                                                                                                                                                              +
                                                                                                                                                                                              +

                                                                                                                                                                                              題目大意

                                                                                                                                                                                              +

                                                                                                                                                                                              題目要求我們反轉一個字符串。

                                                                                                                                                                                              +

                                                                                                                                                                                              解題思路

                                                                                                                                                                                              +

                                                                                                                                                                                              這一題的解題思路是用 2 個指針,指針對撞的思路,來不斷交換首尾元素,即可。

                                                                                                                                                                                              +

                                                                                                                                                                                              來源

                                                                                                                                                                                              + +

                                                                                                                                                                                              解答

                                                                                                                                                                                              +

                                                                                                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0344.Reverse-Stringm/Reverse-String.go

                                                                                                                                                                                              +
                                                                                                                                                                                              package reversestring
                                                                                                                                                                                              +
                                                                                                                                                                                              +func ReverseString(s []byte) {
                                                                                                                                                                                              +    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
                                                                                                                                                                                              +        s[i], s[j] = s[j], s[i]
                                                                                                                                                                                              +    }
                                                                                                                                                                                              +}
                                                                                                                                                                                              +
                                                                                                                                                                                              +
                                                                                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                              + +
                                                                                                                                                                                              + +
                                                                                                                                                                                              +
                                                                                                                                                                                              +
                                                                                                                                                                                              + +

                                                                                                                                                                                              results matching ""

                                                                                                                                                                                              +
                                                                                                                                                                                                + +
                                                                                                                                                                                                +
                                                                                                                                                                                                + +

                                                                                                                                                                                                No results matching ""

                                                                                                                                                                                                + +
                                                                                                                                                                                                +
                                                                                                                                                                                                +
                                                                                                                                                                                                + +
                                                                                                                                                                                                +
                                                                                                                                                                                                + +
                                                                                                                                                                                                + + + + + + +
                                                                                                                                                                                                + + +
                                                                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0347.Top-K-Frequent-Elements/index.html b/Leetcode/0347.Top-K-Frequent-Elements/index.html new file mode 100644 index 000000000..25ab54c8b --- /dev/null +++ b/Leetcode/0347.Top-K-Frequent-Elements/index.html @@ -0,0 +1,4005 @@ + + + + + + + 347. Top K Frequent Elements ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                +
                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                + +
                                                                                                                                                                                                + +
                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                +
                                                                                                                                                                                                + +
                                                                                                                                                                                                +
                                                                                                                                                                                                + +
                                                                                                                                                                                                + +

                                                                                                                                                                                                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.

                                                                                                                                                                                                +

                                                                                                                                                                                                Example 1:

                                                                                                                                                                                                +

                                                                                                                                                                                                Input: nums = [1,1,1,2,2,3], k = 2 +Output: [1,2] +Example 2:

                                                                                                                                                                                                +

                                                                                                                                                                                                Input: nums = [1], k = 1 +Output: [1]

                                                                                                                                                                                                +

                                                                                                                                                                                                Constraints:

                                                                                                                                                                                                +

                                                                                                                                                                                                1 <= nums.length <= 105 +-104 <= nums[i] <= 104 +k is in the range [1, the number of unique elements in the array]. +It is guaranteed that the answer is unique.

                                                                                                                                                                                                +

                                                                                                                                                                                                Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size.

                                                                                                                                                                                                +

                                                                                                                                                                                                Seen this question in a real interview before? 1/4

                                                                                                                                                                                                +
                                                                                                                                                                                                  +
                                                                                                                                                                                                • Accepted 1.9M
                                                                                                                                                                                                • +
                                                                                                                                                                                                • Submissions 3M
                                                                                                                                                                                                • +
                                                                                                                                                                                                • Acceptance Rate 62.7%
                                                                                                                                                                                                • +
                                                                                                                                                                                                +

                                                                                                                                                                                                題目大意

                                                                                                                                                                                                +

                                                                                                                                                                                                解題思路

                                                                                                                                                                                                +

                                                                                                                                                                                                方法一:heap

                                                                                                                                                                                                +

                                                                                                                                                                                                方法一:堆 +思路與演算法

                                                                                                                                                                                                +

                                                                                                                                                                                                首先遍歷整個數組,並使用哈希表記錄每個數字出現的次數,並形成一個「出現次數數組」。 找出原數組的前 k 個高頻元素,就等於找出「出現次數數組」的前 k 大的值。

                                                                                                                                                                                                +

                                                                                                                                                                                                最簡單的做法是為「出現次數數組」排序。 但由於可能有O(N) 個不同的出現次數(其中N 為原數組長度),故總的演算法複雜度會達到O(Nlog⁡N),不符合題目的要求。

                                                                                                                                                                                                +

                                                                                                                                                                                                在這裡,我們可以利用堆的想法:建立一個小頂堆,然後遍歷「出現次數數組」:

                                                                                                                                                                                                +

                                                                                                                                                                                                如果堆的元素個數小於 k,就可以直接插入堆中。 +如果堆的元素個數等於 k,則檢查堆頂與目前出現次數的大小。 如果堆頂較大,表示至少有 k 個數字的出現次數比目前值大,故捨棄目前值;否則,就彈出堆頂,並將目前值插入堆中。 +遍歷完成後,堆中的元素就代表了「出現次數數組」中前 k 大的值。

                                                                                                                                                                                                +

                                                                                                                                                                                                複雜度分析

                                                                                                                                                                                                +

                                                                                                                                                                                                時間複雜度:O(Nlog⁡k), +其中 N 為陣列的長度。 我們先遍歷原數組,並使用雜湊表記錄出現次數,每個元素需要O(1) 的時間,共需O(N) 的時間 。 +隨後,我們遍歷「出現次數數組」,由於堆的大小至多為k,因此每次堆操作需要O(log⁡k)的時間,共需O(Nlog⁡k)的時間。 二者之和為 O(Nlog⁡k)

                                                                                                                                                                                                +

                                                                                                                                                                                                空間複雜度:O(N)。 +雜湊表的大小為O(N),而堆的大小為O(k),共為O(N)

                                                                                                                                                                                                +

                                                                                                                                                                                                方法二: Quick Sort

                                                                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                NameBestAverageWorstMemoryStable
                                                                                                                                                                                                Quick sortn log(n)n log(n)n^2log(n)No
                                                                                                                                                                                                +

                                                                                                                                                                                                使用基於快速排序的方法,求出「出現次數陣列」的前 k 大的值。

                                                                                                                                                                                                +

                                                                                                                                                                                                Big O

                                                                                                                                                                                                +

                                                                                                                                                                                                方法一:heap

                                                                                                                                                                                                +

                                                                                                                                                                                                時間複雜 : O(Nlog⁡k) +空間複雜 : O(N)

                                                                                                                                                                                                +

                                                                                                                                                                                                方法二: Quick Sort

                                                                                                                                                                                                +

                                                                                                                                                                                                時間複雜 : 空間複雜 :

                                                                                                                                                                                                +

                                                                                                                                                                                                來源

                                                                                                                                                                                                + +

                                                                                                                                                                                                解答

                                                                                                                                                                                                +

                                                                                                                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0347.Top-K-Frequent-Elements/main.go

                                                                                                                                                                                                +
                                                                                                                                                                                                package topkfrequentelements
                                                                                                                                                                                                +
                                                                                                                                                                                                +import (
                                                                                                                                                                                                +    "container/heap"
                                                                                                                                                                                                +    "sort"
                                                                                                                                                                                                +)
                                                                                                                                                                                                +
                                                                                                                                                                                                +// 方法一: 使用 PriorityQueue
                                                                                                                                                                                                +// 時間複雜 O(Nlog⁡k), 空間複雜 O(N)
                                                                                                                                                                                                +// 首先遍歷整個數組,並使用哈希表記錄每個數字出現的次數,並形成一個「出現次數數組」
                                                                                                                                                                                                +// 建立一個 PriortyQueue, 將「出現次數數組」丟進去
                                                                                                                                                                                                +// 在把 PriortyQueue pop的值丟到 result
                                                                                                                                                                                                +func TopKFrequent(nums []int, k int) []int {
                                                                                                                                                                                                +    m := make(map[int]int)
                                                                                                                                                                                                +    for i := 0; i < len(nums); i++ {
                                                                                                                                                                                                +        m[nums[i]]++
                                                                                                                                                                                                +    }
                                                                                                                                                                                                +
                                                                                                                                                                                                +    q := PriorityQueue{}
                                                                                                                                                                                                +    for key, count := range m {
                                                                                                                                                                                                +        item := &Item{key: key, count: count}
                                                                                                                                                                                                +        q.PushPQ(item)
                                                                                                                                                                                                +    }
                                                                                                                                                                                                +
                                                                                                                                                                                                +    var result []int
                                                                                                                                                                                                +    for len(result) < k {
                                                                                                                                                                                                +        item := q.PopPQ()
                                                                                                                                                                                                +        result = append(result, item.key)
                                                                                                                                                                                                +    }
                                                                                                                                                                                                +    return result
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +// Item define
                                                                                                                                                                                                +type Item struct {
                                                                                                                                                                                                +    key   int
                                                                                                                                                                                                +    count int
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +/*
                                                                                                                                                                                                +// A PriorityQueue implements heap.Interface and holds Items.
                                                                                                                                                                                                +package heap
                                                                                                                                                                                                +
                                                                                                                                                                                                +import "sort"
                                                                                                                                                                                                +
                                                                                                                                                                                                +type Interface interface {
                                                                                                                                                                                                +    sort.Interface
                                                                                                                                                                                                +    Push(x any) // add x as element Len()
                                                                                                                                                                                                +    Pop() any   // remove and return element Len() - 1.
                                                                                                                                                                                                +}
                                                                                                                                                                                                +*/
                                                                                                                                                                                                +
                                                                                                                                                                                                +type PriorityQueue []*Item
                                                                                                                                                                                                +
                                                                                                                                                                                                +/*
                                                                                                                                                                                                +// An implementation of Interface can be sorted by the routines in this package.
                                                                                                                                                                                                +// The methods refer to elements of the underlying collection by integer index.
                                                                                                                                                                                                +
                                                                                                                                                                                                +    type Interface interface {
                                                                                                                                                                                                +        // Len is the number of elements in the collection.
                                                                                                                                                                                                +        Len() int
                                                                                                                                                                                                +        Less(i, j int) bool
                                                                                                                                                                                                +        Swap(i, j int)
                                                                                                                                                                                                +    }
                                                                                                                                                                                                +*/
                                                                                                                                                                                                +func (pq PriorityQueue) Len() int {
                                                                                                                                                                                                +    return len(pq)
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (pq PriorityQueue) Less(i, j int) bool {
                                                                                                                                                                                                +    // 大到小排序
                                                                                                                                                                                                +    return pq[i].count > pq[j].count
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (pq PriorityQueue) Swap(i, j int) {
                                                                                                                                                                                                +    pq[i], pq[j] = pq[j], pq[i]
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (pg *PriorityQueue) Push(v interface{}) {
                                                                                                                                                                                                +    item := v.(*Item)
                                                                                                                                                                                                +    *pg = append(*pg, item)
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (pg *PriorityQueue) Pop() interface{} {
                                                                                                                                                                                                +    n := len(*pg)
                                                                                                                                                                                                +    item := (*pg)[n-1]
                                                                                                                                                                                                +    *pg = (*pg)[:n-1]
                                                                                                                                                                                                +    return item
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (pg *PriorityQueue) PushPQ(v *Item) {
                                                                                                                                                                                                +    heap.Push(pg, v)
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (pg *PriorityQueue) PopPQ() *Item {
                                                                                                                                                                                                +    return heap.Pop(pg).(*Item)
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +// 方法二: 使用 Quick Sort
                                                                                                                                                                                                +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                                                                +func TopKFrequentQuickSort(nums []int, k int) []int {
                                                                                                                                                                                                +    m := make(map[int]int)
                                                                                                                                                                                                +    for i := 0; i < len(nums); i++ {
                                                                                                                                                                                                +        m[nums[i]]++
                                                                                                                                                                                                +    }
                                                                                                                                                                                                +    values := [][]int{}
                                                                                                                                                                                                +    for key, count := range m {
                                                                                                                                                                                                +        values = append(values, []int{key, count})
                                                                                                                                                                                                +    }
                                                                                                                                                                                                +
                                                                                                                                                                                                +    result := []int{}
                                                                                                                                                                                                +    sort.Sort(sortValue(values))
                                                                                                                                                                                                +
                                                                                                                                                                                                +    for i := 0; i < k; i++ {
                                                                                                                                                                                                +        result = append(result, values[i][0])
                                                                                                                                                                                                +    }
                                                                                                                                                                                                +    return result
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +type sortValue [][]int
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (s sortValue) Len() int {
                                                                                                                                                                                                +    return len(s)
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (s sortValue) Less(i, j int) bool {
                                                                                                                                                                                                +    return s[i][1] > s[j][1]
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +func (s sortValue) Swap(i, j int) {
                                                                                                                                                                                                +    s[i], s[j] = s[j], s[i]
                                                                                                                                                                                                +}
                                                                                                                                                                                                +
                                                                                                                                                                                                +

                                                                                                                                                                                                Benchmark

                                                                                                                                                                                                +
                                                                                                                                                                                                goos: darwin
                                                                                                                                                                                                +goarch: amd64
                                                                                                                                                                                                +pkg: LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements
                                                                                                                                                                                                +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                                +BenchmarkTopKFrequent-8                  1875834               648.6 ns/op           200 B/op         11 allocs/op
                                                                                                                                                                                                +BenchmarkTopKFrequentQuickSort-8         1830498               704.2 ns/op           312 B/op         11 allocs/op
                                                                                                                                                                                                +PASS
                                                                                                                                                                                                +ok      LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements    3.831s
                                                                                                                                                                                                +
                                                                                                                                                                                                +
                                                                                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                + +
                                                                                                                                                                                                + +
                                                                                                                                                                                                +
                                                                                                                                                                                                +
                                                                                                                                                                                                + +

                                                                                                                                                                                                results matching ""

                                                                                                                                                                                                +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  + +

                                                                                                                                                                                                  No results matching ""

                                                                                                                                                                                                  + +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  + + + + + + +
                                                                                                                                                                                                  + + +
                                                                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0347.Top-K-Frequent-Elements/main.go b/Leetcode/0347.Top-K-Frequent-Elements/main.go new file mode 100644 index 000000000..de58402d3 --- /dev/null +++ b/Leetcode/0347.Top-K-Frequent-Elements/main.go @@ -0,0 +1,131 @@ +package topkfrequentelements + +import ( + "container/heap" + "sort" +) + +// ๆ–นๆณ•ไธ€: ไฝฟ็”จ PriorityQueue +// ๆ™‚้–“่ค‡้›œ O(Nlogโกk), ็ฉบ้–“่ค‡้›œ O(N) +// ้ฆ–ๅ…ˆ้ๆญทๆ•ดๅ€‹ๆ•ธ็ต„๏ผŒไธฆไฝฟ็”จๅ“ˆๅธŒ่กจ่จ˜้Œ„ๆฏๅ€‹ๆ•ธๅญ—ๅ‡บ็พ็š„ๆฌกๆ•ธ๏ผŒไธฆๅฝขๆˆไธ€ๅ€‹ใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€ +// ๅปบ็ซ‹ไธ€ๅ€‹ PriortyQueue, ๅฐ‡ใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€ไธŸ้€ฒๅŽป +// ๅœจๆŠŠ PriortyQueue pop็š„ๅ€ผไธŸๅˆฐ result +func TopKFrequent(nums []int, k int) []int { + m := make(map[int]int) + for i := 0; i < len(nums); i++ { + m[nums[i]]++ + } + + q := PriorityQueue{} + for key, count := range m { + item := &Item{key: key, count: count} + q.PushPQ(item) + } + + var result []int + for len(result) < k { + item := q.PopPQ() + result = append(result, item.key) + } + return result +} + +// Item define +type Item struct { + key int + count int +} + +/* +// A PriorityQueue implements heap.Interface and holds Items. +package heap + +import "sort" + +type Interface interface { + sort.Interface + Push(x any) // add x as element Len() + Pop() any // remove and return element Len() - 1. +} +*/ + +type PriorityQueue []*Item + +/* +// An implementation of Interface can be sorted by the routines in this package. +// The methods refer to elements of the underlying collection by integer index. + + type Interface interface { + // Len is the number of elements in the collection. + Len() int + Less(i, j int) bool + Swap(i, j int) + } +*/ +func (pq PriorityQueue) Len() int { + return len(pq) +} + +func (pq PriorityQueue) Less(i, j int) bool { + // ๅคงๅˆฐๅฐๆŽ’ๅบ + return pq[i].count > pq[j].count +} + +func (pq PriorityQueue) Swap(i, j int) { + pq[i], pq[j] = pq[j], pq[i] +} + +func (pg *PriorityQueue) Push(v interface{}) { + item := v.(*Item) + *pg = append(*pg, item) +} + +func (pg *PriorityQueue) Pop() interface{} { + n := len(*pg) + item := (*pg)[n-1] + *pg = (*pg)[:n-1] + return item +} + +func (pg *PriorityQueue) PushPQ(v *Item) { + heap.Push(pg, v) +} + +func (pg *PriorityQueue) PopPQ() *Item { + return heap.Pop(pg).(*Item) +} + +// ๆ–นๆณ•ไบŒ: ไฝฟ็”จ Quick Sort +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +func TopKFrequentQuickSort(nums []int, k int) []int { + m := make(map[int]int) + for i := 0; i < len(nums); i++ { + m[nums[i]]++ + } + values := [][]int{} + for key, count := range m { + values = append(values, []int{key, count}) + } + + result := []int{} + sort.Sort(sortValue(values)) + + for i := 0; i < k; i++ { + result = append(result, values[i][0]) + } + return result +} + +type sortValue [][]int + +func (s sortValue) Len() int { + return len(s) +} + +func (s sortValue) Less(i, j int) bool { + return s[i][1] > s[j][1] +} + +func (s sortValue) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} diff --git a/Leetcode/0347.Top-K-Frequent-Elements/main_test.go b/Leetcode/0347.Top-K-Frequent-Elements/main_test.go new file mode 100644 index 000000000..19e0e07f7 --- /dev/null +++ b/Leetcode/0347.Top-K-Frequent-Elements/main_test.go @@ -0,0 +1,66 @@ +package topkfrequentelements + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []int + arg2 int + want []int +}{ + { + []int{1, 1, 1, 2, 2, 3}, + 2, + []int{1, 2}, + }, + { + []int{1}, + 1, + []int{1}, + }, +} + +func TestTopKFrequent(t *testing.T) { + for _, tt := range tests { + if got := TopKFrequent(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestTopKFrequentQuickSort(t *testing.T) { + for _, tt := range tests { + if got := TopKFrequentQuickSort(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkTopKFrequent(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + TopKFrequent(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkTopKFrequentQuickSort(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + TopKFrequentQuickSort(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements -bench=. +go test -benchmem -run=none LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements -bench=. ๎‚ฒ ๏€Œ ๎‚ณ 100% ๏‰€ ๎‚ฒ 14:39:46 ๏€— +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkTopKFrequent-8 1875834 648.6 ns/op 200 B/op 11 allocs/op +BenchmarkTopKFrequentQuickSort-8 1830498 704.2 ns/op 312 B/op 11 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements 3.831s +*/ diff --git a/Leetcode/0354.Russian-Doll-Envelopes/index.html b/Leetcode/0354.Russian-Doll-Envelopes/index.html new file mode 100644 index 000000000..e5ca3c7cd --- /dev/null +++ b/Leetcode/0354.Russian-Doll-Envelopes/index.html @@ -0,0 +1,3937 @@ + + + + + + + 0354. Russian Doll Envelope ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  + +

                                                                                                                                                                                                  354. Russian Doll Envelope

                                                                                                                                                                                                  題目

                                                                                                                                                                                                  +

                                                                                                                                                                                                  You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope.

                                                                                                                                                                                                  +

                                                                                                                                                                                                  One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height.

                                                                                                                                                                                                  +

                                                                                                                                                                                                  Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other).

                                                                                                                                                                                                  +

                                                                                                                                                                                                  Note: You cannot rotate an envelope.

                                                                                                                                                                                                  +

                                                                                                                                                                                                  Example 1:

                                                                                                                                                                                                  +
                                                                                                                                                                                                  Input: envelopes = [[5,4],[6,4],[6,7],[2,3]]
                                                                                                                                                                                                  +Output: 3
                                                                                                                                                                                                  +Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]).
                                                                                                                                                                                                  +

                                                                                                                                                                                                  Example 2:

                                                                                                                                                                                                  +
                                                                                                                                                                                                  Input: envelopes = [[1,1],[1,1],[1,1]]
                                                                                                                                                                                                  +Output: 1
                                                                                                                                                                                                  +

                                                                                                                                                                                                  Constraints:

                                                                                                                                                                                                  +
                                                                                                                                                                                                    +
                                                                                                                                                                                                  • 1 <= envelopes.length <= 105
                                                                                                                                                                                                  • +
                                                                                                                                                                                                  • envelopes[i].length == 2
                                                                                                                                                                                                  • +
                                                                                                                                                                                                  • 1 <= wi, hi <= 105
                                                                                                                                                                                                  • +
                                                                                                                                                                                                  +

                                                                                                                                                                                                  題目大意

                                                                                                                                                                                                  +

                                                                                                                                                                                                  給一些信封, 每個信封用寬度和高度的整數對形式(w,h)表示, 當一個信封A的寬度和高度都比另一個信封B大的時候, 則B就可以放進A裡. +計算出最多有多少信封能組成一組

                                                                                                                                                                                                  +

                                                                                                                                                                                                  解題思路

                                                                                                                                                                                                  +

                                                                                                                                                                                                  先對寬度w進行升序排序, 如果遇到w相同的情況, 則按照高度進行降序排序. +之後把所有的h最為一個array, 對此array做 最長遞增子序列(Longest Increasing Subsequence, LIS)的長度就是答案

                                                                                                                                                                                                  +

                                                                                                                                                                                                  此題是二維的LIS問題, 一維LIS參考 https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0300.Longest-Increasing-Subsequence/main.go +三維 Leetcode No.1691

                                                                                                                                                                                                  +

                                                                                                                                                                                                  來源

                                                                                                                                                                                                  + +

                                                                                                                                                                                                  解答

                                                                                                                                                                                                  +

                                                                                                                                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0354.Russian-Doll-Envelopes/main.go

                                                                                                                                                                                                  +
                                                                                                                                                                                                  package russiandollenvelopes
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +import (
                                                                                                                                                                                                  +    longestincreasingsubsequence "LeetcodeGolang/Leetcode/0300.Longest-Increasing-Subsequence"
                                                                                                                                                                                                  +    "sort"
                                                                                                                                                                                                  +)
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +type sortEnvelopes [][]int
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +func (s sortEnvelopes) Len() int {
                                                                                                                                                                                                  +    return len(s)
                                                                                                                                                                                                  +}
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +func (s sortEnvelopes) Less(i, j int) bool {
                                                                                                                                                                                                  +    if s[i][0] == s[j][0] {
                                                                                                                                                                                                  +        // 遇到w相同的情況, 則按照高度進行降序排序
                                                                                                                                                                                                  +        return s[i][1] > s[j][1]
                                                                                                                                                                                                  +    }
                                                                                                                                                                                                  +    // 對寬度w進行升序排序
                                                                                                                                                                                                  +    return s[i][0] < s[j][0]
                                                                                                                                                                                                  +}
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +func (s sortEnvelopes) Swap(i, j int) {
                                                                                                                                                                                                  +    s[i], s[j] = s[j], s[i]
                                                                                                                                                                                                  +}
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +func MaxEnvelopes(envelopes [][]int) int {
                                                                                                                                                                                                  +    // 先對寬度w進行升序排序, 如果遇到w相同的情況, 則按照高度進行降序排序.
                                                                                                                                                                                                  +    sort.Sort(sortEnvelopes(envelopes))
                                                                                                                                                                                                  +    // fmt.Println(envelopes)
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +    // 所有的h最為一個array, 對此array做 最長遞增子序列(Longest Increasing Subsequence, LIS)的長度就是答案
                                                                                                                                                                                                  +    height := make([]int, len(envelopes))
                                                                                                                                                                                                  +    for i := 0; i < len(envelopes); i++ {
                                                                                                                                                                                                  +        height[i] = envelopes[i][1]
                                                                                                                                                                                                  +    }
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +    //  DP + 二分搜尋:patience sorting. O(nlogn)
                                                                                                                                                                                                  +    return longestincreasingsubsequence.LengthOfLISPatience(height)
                                                                                                                                                                                                  +}
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +func MaxEnvelopes2(envelopes [][]int) int {
                                                                                                                                                                                                  +    // 先對寬度w進行升序排序, 如果遇到w相同的情況, 則按照高度進行降序排序.
                                                                                                                                                                                                  +    sort.Sort(sortEnvelopes(envelopes))
                                                                                                                                                                                                  +    // fmt.Println(envelopes)
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +    // 最長遞增子序列(Longest Increasing Subsequence, LIS)的長度就是答案
                                                                                                                                                                                                  +    dp := []int{}
                                                                                                                                                                                                  +    for _, e := range envelopes {
                                                                                                                                                                                                  +        left, right := 0, len(dp)
                                                                                                                                                                                                  +        for left < right {
                                                                                                                                                                                                  +            mid := left + (right-left)/2
                                                                                                                                                                                                  +            if dp[mid] > e[1] {
                                                                                                                                                                                                  +                // 現在的牌比堆小, 所小範圍
                                                                                                                                                                                                  +                right = mid
                                                                                                                                                                                                  +            } else if dp[mid] < e[1] {
                                                                                                                                                                                                  +                // 現在的牌比堆大
                                                                                                                                                                                                  +                left = mid + 1
                                                                                                                                                                                                  +            } else {
                                                                                                                                                                                                  +                right = mid
                                                                                                                                                                                                  +            }
                                                                                                                                                                                                  +        }
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +        // 沒有找到堆, 建立一個新的堆
                                                                                                                                                                                                  +        if left == len(dp) {
                                                                                                                                                                                                  +            dp = append(dp, e[1])
                                                                                                                                                                                                  +        }
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +        // 再把這張牌放在堆的頂端
                                                                                                                                                                                                  +        dp[left] = e[1]
                                                                                                                                                                                                  +    }
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +    return len(dp)
                                                                                                                                                                                                  +}
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +/*
                                                                                                                                                                                                  +func Sort(data Interface) {
                                                                                                                                                                                                  +    n := data.Len()
                                                                                                                                                                                                  +    quickSort(data, 0, n, maxDepth(n))
                                                                                                                                                                                                  +}
                                                                                                                                                                                                  +type Interface interface {
                                                                                                                                                                                                  +    // Len is the number of elements in the collection.
                                                                                                                                                                                                  +    Len() int
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +    // Less reports whether the element with index i
                                                                                                                                                                                                  +    // must sort before the element with index j.
                                                                                                                                                                                                  +    //
                                                                                                                                                                                                  +    // If both Less(i, j) and Less(j, i) are false,
                                                                                                                                                                                                  +    // then the elements at index i and j are considered equal.
                                                                                                                                                                                                  +    // Sort may place equal elements in any order in the final result,
                                                                                                                                                                                                  +    // while Stable preserves the original input order of equal elements.
                                                                                                                                                                                                  +    //
                                                                                                                                                                                                  +    // Less must describe a transitive ordering:
                                                                                                                                                                                                  +    //  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
                                                                                                                                                                                                  +    //  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
                                                                                                                                                                                                  +    //
                                                                                                                                                                                                  +    // Note that floating-point comparison (the < operator on float32 or float64 values)
                                                                                                                                                                                                  +    // is not a transitive ordering when not-a-number (NaN) values are involved.
                                                                                                                                                                                                  +    // See Float64Slice.Less for a correct implementation for floating-point values.
                                                                                                                                                                                                  +    Less(i, j int) bool
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +    // Swap swaps the elements with indexes i and j.
                                                                                                                                                                                                  +    Swap(i, j int)
                                                                                                                                                                                                  +}
                                                                                                                                                                                                  +*/
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=.
                                                                                                                                                                                                  +goos: darwin
                                                                                                                                                                                                  +goarch: amd64
                                                                                                                                                                                                  +pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes
                                                                                                                                                                                                  +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                                  +BenchmarkMaxEnvelopes-8          9067520               167.0 ns/op            88 B/op          3 allocs/op
                                                                                                                                                                                                  +BenchmarkMaxEnvelopes2-8         6726646               214.9 ns/op            80 B/op          4 allocs/op
                                                                                                                                                                                                  +PASS
                                                                                                                                                                                                  +ok      LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes     6.237s
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  + +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  +
                                                                                                                                                                                                  + +

                                                                                                                                                                                                  results matching ""

                                                                                                                                                                                                  +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    + +

                                                                                                                                                                                                    No results matching ""

                                                                                                                                                                                                    + +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    + + + + + + +
                                                                                                                                                                                                    + + +
                                                                                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0354.Russian-Doll-Envelopes/main.go b/Leetcode/0354.Russian-Doll-Envelopes/main.go new file mode 100644 index 000000000..8ffb917d7 --- /dev/null +++ b/Leetcode/0354.Russian-Doll-Envelopes/main.go @@ -0,0 +1,105 @@ +package russiandollenvelopes + +import ( + longestincreasingsubsequence "LeetcodeGolang/Leetcode/0300.Longest-Increasing-Subsequence" + "sort" +) + +type sortEnvelopes [][]int + +func (s sortEnvelopes) Len() int { + return len(s) +} + +func (s sortEnvelopes) Less(i, j int) bool { + if s[i][0] == s[j][0] { + // ้‡ๅˆฐw็›ธๅŒ็š„ๆƒ…ๆณ, ๅ‰‡ๆŒ‰็…ง้ซ˜ๅบฆ้€ฒ่กŒ้™ๅบๆŽ’ๅบ + return s[i][1] > s[j][1] + } + // ๅฐๅฏฌๅบฆw้€ฒ่กŒๅ‡ๅบๆŽ’ๅบ + return s[i][0] < s[j][0] +} + +func (s sortEnvelopes) Swap(i, j int) { + s[i], s[j] = s[j], s[i] +} + +func MaxEnvelopes(envelopes [][]int) int { + // ๅ…ˆๅฐๅฏฌๅบฆw้€ฒ่กŒๅ‡ๅบๆŽ’ๅบ, ๅฆ‚ๆžœ้‡ๅˆฐw็›ธๅŒ็š„ๆƒ…ๆณ, ๅ‰‡ๆŒ‰็…ง้ซ˜ๅบฆ้€ฒ่กŒ้™ๅบๆŽ’ๅบ. + sort.Sort(sortEnvelopes(envelopes)) + // fmt.Println(envelopes) + + // ๆ‰€ๆœ‰็š„hๆœ€็‚บไธ€ๅ€‹array, ๅฐๆญคarrayๅš ๆœ€้•ท้žๅขžๅญๅบๅˆ—(Longest Increasing Subsequence, LIS)็š„้•ทๅบฆๅฐฑๆ˜ฏ็ญ”ๆกˆ + height := make([]int, len(envelopes)) + for i := 0; i < len(envelopes); i++ { + height[i] = envelopes[i][1] + } + + // DP + ไบŒๅˆ†ๆœๅฐ‹:patience sorting. O(nlogn) + return longestincreasingsubsequence.LengthOfLISPatience(height) +} + +func MaxEnvelopes2(envelopes [][]int) int { + // ๅ…ˆๅฐๅฏฌๅบฆw้€ฒ่กŒๅ‡ๅบๆŽ’ๅบ, ๅฆ‚ๆžœ้‡ๅˆฐw็›ธๅŒ็š„ๆƒ…ๆณ, ๅ‰‡ๆŒ‰็…ง้ซ˜ๅบฆ้€ฒ่กŒ้™ๅบๆŽ’ๅบ. + sort.Sort(sortEnvelopes(envelopes)) + // fmt.Println(envelopes) + + // ๆœ€้•ท้žๅขžๅญๅบๅˆ—(Longest Increasing Subsequence, LIS)็š„้•ทๅบฆๅฐฑๆ˜ฏ็ญ”ๆกˆ + dp := []int{} + for _, e := range envelopes { + left, right := 0, len(dp) + for left < right { + mid := left + (right-left)/2 + if dp[mid] > e[1] { + // ็พๅœจ็š„็‰Œๆฏ”ๅ †ๅฐ, ๆ‰€ๅฐ็ฏ„ๅœ + right = mid + } else if dp[mid] < e[1] { + // ็พๅœจ็š„็‰Œๆฏ”ๅ †ๅคง + left = mid + 1 + } else { + right = mid + } + } + + // ๆฒ’ๆœ‰ๆ‰พๅˆฐๅ †, ๅปบ็ซ‹ไธ€ๅ€‹ๆ–ฐ็š„ๅ † + if left == len(dp) { + dp = append(dp, e[1]) + } + + // ๅ†ๆŠŠ้€™ๅผต็‰Œๆ”พๅœจๅ †็š„้ ‚็ซฏ + dp[left] = e[1] + } + + return len(dp) +} + +/* +func Sort(data Interface) { + n := data.Len() + quickSort(data, 0, n, maxDepth(n)) +} +type Interface interface { + // Len is the number of elements in the collection. + Len() int + + // Less reports whether the element with index i + // must sort before the element with index j. + // + // If both Less(i, j) and Less(j, i) are false, + // then the elements at index i and j are considered equal. + // Sort may place equal elements in any order in the final result, + // while Stable preserves the original input order of equal elements. + // + // Less must describe a transitive ordering: + // - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well. + // - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well. + // + // Note that floating-point comparison (the < operator on float32 or float64 values) + // is not a transitive ordering when not-a-number (NaN) values are involved. + // See Float64Slice.Less for a correct implementation for floating-point values. + Less(i, j int) bool + + // Swap swaps the elements with indexes i and j. + Swap(i, j int) +} +*/ diff --git a/Leetcode/0354.Russian-Doll-Envelopes/main_test.go b/Leetcode/0354.Russian-Doll-Envelopes/main_test.go new file mode 100644 index 000000000..fd3da39ca --- /dev/null +++ b/Leetcode/0354.Russian-Doll-Envelopes/main_test.go @@ -0,0 +1,59 @@ +package russiandollenvelopes + +import "testing" + +var tests = []struct { + arg1 [][]int + want int +}{ + { + [][]int{{5, 4}, {6, 4}, {6, 7}, {2, 3}}, + 3, + }, + { + [][]int{{1, 1}, {1, 1}, {1, 1}}, + 1, + }, +} + +func TestMaxEnvelopes(t *testing.T) { + for _, tt := range tests { + if got := MaxEnvelopes(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMaxEnvelopes2(t *testing.T) { + for _, tt := range tests { + if got := MaxEnvelopes2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkMaxEnvelopes(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxEnvelopes(tests[0].arg1) + } +} + +func BenchmarkMaxEnvelopes2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxEnvelopes2(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkMaxEnvelopes-8 9067520 167.0 ns/op 88 B/op 3 allocs/op +BenchmarkMaxEnvelopes2-8 6726646 214.9 ns/op 80 B/op 4 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes 6.237s +*/ diff --git a/Leetcode/0380.Insert-Delete-GetRandom-O1/index.html b/Leetcode/0380.Insert-Delete-GetRandom-O1/index.html new file mode 100644 index 000000000..a1fdfc189 --- /dev/null +++ b/Leetcode/0380.Insert-Delete-GetRandom-O1/index.html @@ -0,0 +1,3893 @@ + + + + + + + 380. Insert Delete GetRandom O(1) ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    + +

                                                                                                                                                                                                    380. Insert Delete GetRandom O(1)

                                                                                                                                                                                                    題目

                                                                                                                                                                                                    +

                                                                                                                                                                                                    Implement the RandomizedSet class:

                                                                                                                                                                                                    +

                                                                                                                                                                                                    RandomizedSet() Initializes the RandomizedSet object. +bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. +bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. +int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. +You must implement the functions of the class such that each function works in average O(1) time complexity.

                                                                                                                                                                                                    +

                                                                                                                                                                                                    Example 1:

                                                                                                                                                                                                    +

                                                                                                                                                                                                    Input +["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] +[[], [1], [2], [2], [], [1], [2], []] +Output +[null, true, false, true, 2, true, false, 2]

                                                                                                                                                                                                    +

                                                                                                                                                                                                    Explanation +RandomizedSet randomizedSet = new RandomizedSet(); +randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. +randomizedSet.remove(2); // Returns false as 2 does not exist in the set. +randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. +randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. +randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. +randomizedSet.insert(2); // 2 was already in the set, so return false. +randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2.

                                                                                                                                                                                                    +

                                                                                                                                                                                                    Constraints:

                                                                                                                                                                                                    +

                                                                                                                                                                                                    -231 <= val <= 231 - 1 +At most 2 * 105 calls will be made to insert, remove, and getRandom. +There will be at least one element in the data structure when getRandom is called.

                                                                                                                                                                                                    +

                                                                                                                                                                                                    題目大意

                                                                                                                                                                                                    +

                                                                                                                                                                                                    解題思路

                                                                                                                                                                                                    +

                                                                                                                                                                                                    用map紀錄每個元素的index

                                                                                                                                                                                                    +

                                                                                                                                                                                                    Big O

                                                                                                                                                                                                    +

                                                                                                                                                                                                    時間複雜 : O(1) +空間複雜 : O(n)

                                                                                                                                                                                                    +

                                                                                                                                                                                                    來源

                                                                                                                                                                                                    + +

                                                                                                                                                                                                    解答

                                                                                                                                                                                                    +

                                                                                                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0380.Insert-Delete-GetRandom-O1/main.go

                                                                                                                                                                                                    +
                                                                                                                                                                                                    package insertdeletegetrandom
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +import "math/rand"
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +// 時間複雜 O(1), 空間複雜 O(n)
                                                                                                                                                                                                    +type RandomizedSet struct {
                                                                                                                                                                                                    +    arr  []int
                                                                                                                                                                                                    +    set  map[int]int
                                                                                                                                                                                                    +    size int
                                                                                                                                                                                                    +}
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +func Constructor() RandomizedSet {
                                                                                                                                                                                                    +    arr := make([]int, 0)
                                                                                                                                                                                                    +    set := make(map[int]int)
                                                                                                                                                                                                    +    size := 0
                                                                                                                                                                                                    +    return RandomizedSet{arr, set, size}
                                                                                                                                                                                                    +}
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +func (this *RandomizedSet) Insert(val int) bool {
                                                                                                                                                                                                    +    if _, ok := this.set[val]; ok {
                                                                                                                                                                                                    +        return false
                                                                                                                                                                                                    +    }
                                                                                                                                                                                                    +    this.set[val] = this.size
                                                                                                                                                                                                    +    this.size++
                                                                                                                                                                                                    +    this.arr = append(this.arr, val)
                                                                                                                                                                                                    +    return true
                                                                                                                                                                                                    +}
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +func (this *RandomizedSet) Remove(val int) bool {
                                                                                                                                                                                                    +    index, ok := this.set[val]
                                                                                                                                                                                                    +    if !ok {
                                                                                                                                                                                                    +        return false
                                                                                                                                                                                                    +    }
                                                                                                                                                                                                    +    // swapping
                                                                                                                                                                                                    +    lastValue := this.arr[this.size-1]
                                                                                                                                                                                                    +    this.arr[index] = lastValue
                                                                                                                                                                                                    +    this.set[lastValue] = index
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +    // Remove last value
                                                                                                                                                                                                    +    this.arr = this.arr[:this.size-1]
                                                                                                                                                                                                    +    delete(this.set, val)
                                                                                                                                                                                                    +    this.size--
                                                                                                                                                                                                    +    return true
                                                                                                                                                                                                    +}
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +func (this *RandomizedSet) GetRandom() int {
                                                                                                                                                                                                    +    index := rand.Intn(this.size)
                                                                                                                                                                                                    +    return this.arr[index]
                                                                                                                                                                                                    +}
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +/**
                                                                                                                                                                                                    + * Your RandomizedSet object will be instantiated and called as such:
                                                                                                                                                                                                    + * obj := Constructor();
                                                                                                                                                                                                    + * param_1 := obj.Insert(val);
                                                                                                                                                                                                    + * param_2 := obj.Remove(val);
                                                                                                                                                                                                    + * param_3 := obj.GetRandom();
                                                                                                                                                                                                    + */
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +

                                                                                                                                                                                                    Benchmark

                                                                                                                                                                                                    +
                                                                                                                                                                                                    
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +

                                                                                                                                                                                                    Follow up

                                                                                                                                                                                                    +

                                                                                                                                                                                                    如果允許重複, 譬如多個1

                                                                                                                                                                                                    +

                                                                                                                                                                                                    0381.Insert-Delete-GetRandom-O1-Duplicates-allowed #Hard

                                                                                                                                                                                                    +
                                                                                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    + +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    +
                                                                                                                                                                                                    + +

                                                                                                                                                                                                    results matching ""

                                                                                                                                                                                                    +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      + +

                                                                                                                                                                                                      No results matching ""

                                                                                                                                                                                                      + +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      + + + + + + +
                                                                                                                                                                                                      + + +
                                                                                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0380.Insert-Delete-GetRandom-O1/main.go b/Leetcode/0380.Insert-Delete-GetRandom-O1/main.go new file mode 100644 index 000000000..4d057e76c --- /dev/null +++ b/Leetcode/0380.Insert-Delete-GetRandom-O1/main.go @@ -0,0 +1,57 @@ +package insertdeletegetrandom + +import "math/rand" + +// ๆ™‚้–“่ค‡้›œ O(1), ็ฉบ้–“่ค‡้›œ O(n) +type RandomizedSet struct { + arr []int + set map[int]int + size int +} + +func Constructor() RandomizedSet { + arr := make([]int, 0) + set := make(map[int]int) + size := 0 + return RandomizedSet{arr, set, size} +} + +func (this *RandomizedSet) Insert(val int) bool { + if _, ok := this.set[val]; ok { + return false + } + this.set[val] = this.size + this.size++ + this.arr = append(this.arr, val) + return true +} + +func (this *RandomizedSet) Remove(val int) bool { + index, ok := this.set[val] + if !ok { + return false + } + // swapping + lastValue := this.arr[this.size-1] + this.arr[index] = lastValue + this.set[lastValue] = index + + // Remove last value + this.arr = this.arr[:this.size-1] + delete(this.set, val) + this.size-- + return true +} + +func (this *RandomizedSet) GetRandom() int { + index := rand.Intn(this.size) + return this.arr[index] +} + +/** + * Your RandomizedSet object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Insert(val); + * param_2 := obj.Remove(val); + * param_3 := obj.GetRandom(); + */ diff --git a/Leetcode/0380.Insert-Delete-GetRandom-O1/main_test.go b/Leetcode/0380.Insert-Delete-GetRandom-O1/main_test.go new file mode 100644 index 000000000..f653cfac8 --- /dev/null +++ b/Leetcode/0380.Insert-Delete-GetRandom-O1/main_test.go @@ -0,0 +1,47 @@ +package insertdeletegetrandom + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 []string + arg2 []int + want []interface{} +}{ + { + []string{ + "RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom", + }, + []int{ + 0, 1, 1, 2, 0, 1, 2, 0, + }, + []interface{}{ + nil, true, true, true, 2, false, false, 2, + }, + }, +} + +func TestInsertdeletegetrandom(t *testing.T) { + for _, tt := range tests { + result := []interface{}{} + var rSet RandomizedSet + for i := 0; i < len(tt.arg1); i++ { + switch tt.arg1[i] { + case "RandomizedSet": + rSet = Constructor() + result = append(result, nil) + case "insert": + result = append(result, rSet.Insert(tt.arg2[i])) + case "remove": + result = append(result, rSet.Remove(tt.arg2[i])) + case "getRandom": + result = append(result, rSet.GetRandom()) + } + } + if !reflect.DeepEqual(result, tt.want) { + t.Errorf("got = %v, want = %v", result, tt.want) + } + } +} diff --git a/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/index.html b/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/index.html new file mode 100644 index 000000000..c97362dd9 --- /dev/null +++ b/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/index.html @@ -0,0 +1,3918 @@ + + + + + + + 381.Insert Delete GetRandom O(1) Duplicates allowed ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      + +

                                                                                                                                                                                                      381.Insert Delete GetRandom O(1) Duplicates allowed

                                                                                                                                                                                                      題目

                                                                                                                                                                                                      +

                                                                                                                                                                                                      題目大意

                                                                                                                                                                                                      +

                                                                                                                                                                                                      解題思路

                                                                                                                                                                                                      +

                                                                                                                                                                                                      RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.

                                                                                                                                                                                                      +

                                                                                                                                                                                                      Implement the RandomizedCollection class:

                                                                                                                                                                                                      +

                                                                                                                                                                                                      RandomizedCollection() Initializes the empty RandomizedCollection object. +bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise. +bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them. +int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains. +You must implement the functions of the class such that each function works on average O(1) time complexity.

                                                                                                                                                                                                      +

                                                                                                                                                                                                      Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection.

                                                                                                                                                                                                      +

                                                                                                                                                                                                      Example 1:

                                                                                                                                                                                                      +

                                                                                                                                                                                                      Input +["RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom"] +[[], [1], [1], [2], [], [1], []] +Output +[null, true, false, true, 2, true, 1]

                                                                                                                                                                                                      +

                                                                                                                                                                                                      Explanation +RandomizedCollection randomizedCollection = new RandomizedCollection(); +randomizedCollection.insert(1); // return true since the collection does not contain 1. + // Inserts 1 into the collection. +randomizedCollection.insert(1); // return false since the collection contains 1. + // Inserts another 1 into the collection. Collection now contains [1,1]. +randomizedCollection.insert(2); // return true since the collection does not contain 2. + // Inserts 2 into the collection. Collection now contains [1,1,2]. +randomizedCollection.getRandom(); // getRandom should: + // - return 1 with probability 2/3, or + // - return 2 with probability 1/3. +randomizedCollection.remove(1); // return true since the collection contains 1. + // Removes 1 from the collection. Collection now contains [1,2]. +randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely.

                                                                                                                                                                                                      +

                                                                                                                                                                                                      Constraints:

                                                                                                                                                                                                      +

                                                                                                                                                                                                      -231 <= val <= 231 - 1 +At most 2 * 105 calls in total will be made to insert, remove, and getRandom. +There will be at least one element in the data structure when getRandom is called.

                                                                                                                                                                                                      +

                                                                                                                                                                                                      Big O

                                                                                                                                                                                                      +

                                                                                                                                                                                                      時間複雜 : O(1) +空間複雜 : O(n)

                                                                                                                                                                                                      +

                                                                                                                                                                                                      來源

                                                                                                                                                                                                      + +

                                                                                                                                                                                                      解答

                                                                                                                                                                                                      +

                                                                                                                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main.go

                                                                                                                                                                                                      +
                                                                                                                                                                                                      package insertdeletegetrandomo1duplicatesallowed
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +import (
                                                                                                                                                                                                      +    "math/rand"
                                                                                                                                                                                                      +)
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +// 時間複雜 O(1), 空間複雜 O(n)
                                                                                                                                                                                                      +type RandomizedCollection struct {
                                                                                                                                                                                                      +    arr  []int
                                                                                                                                                                                                      +    set  map[int]map[int]struct{}
                                                                                                                                                                                                      +    size int
                                                                                                                                                                                                      +}
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +func Constructor() RandomizedCollection {
                                                                                                                                                                                                      +    arr := make([]int, 0)
                                                                                                                                                                                                      +    set := make(map[int]map[int]struct{})
                                                                                                                                                                                                      +    size := 0
                                                                                                                                                                                                      +    return RandomizedCollection{arr, set, size}
                                                                                                                                                                                                      +}
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +func (this *RandomizedCollection) Insert(val int) bool {
                                                                                                                                                                                                      +    ids, ok := this.set[val]
                                                                                                                                                                                                      +    if !ok {
                                                                                                                                                                                                      +        // 沒有此數字了, 建立一個index的map
                                                                                                                                                                                                      +        ids = map[int]struct{}{}
                                                                                                                                                                                                      +        this.set[val] = ids
                                                                                                                                                                                                      +    }
                                                                                                                                                                                                      +    // index的map, key為當前最後的index, value為空的struct{}{}
                                                                                                                                                                                                      +    ids[this.size] = struct{}{}
                                                                                                                                                                                                      +    this.arr = append(this.arr, val)
                                                                                                                                                                                                      +    this.size++
                                                                                                                                                                                                      +    return !ok
                                                                                                                                                                                                      +}
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +func (this *RandomizedCollection) Remove(val int) bool {
                                                                                                                                                                                                      +    ids, ok := this.set[val]
                                                                                                                                                                                                      +    if !ok {
                                                                                                                                                                                                      +        return false
                                                                                                                                                                                                      +    }
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +    // 找出此val的的index, 並且把最後一個index的map刪除, 並且把此index的value設為空的struct{}{}
                                                                                                                                                                                                      +    var i int
                                                                                                                                                                                                      +    for id := range ids {
                                                                                                                                                                                                      +        i = id
                                                                                                                                                                                                      +        break
                                                                                                                                                                                                      +    }
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +    // 將最後一筆移到要替換的id
                                                                                                                                                                                                      +    this.arr[i] = this.arr[this.size-1]
                                                                                                                                                                                                      +    delete(ids, i)
                                                                                                                                                                                                      +    // 因為把最後一個元素移到前面了
                                                                                                                                                                                                      +    delete(this.set[this.arr[i]], this.size-1)
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +    if i < this.size-1 {
                                                                                                                                                                                                      +        // fmt.Printf("i =%d, this.size =%d\t", i, this.size)
                                                                                                                                                                                                      +        this.set[this.arr[i]][i] = struct{}{}
                                                                                                                                                                                                      +    }
                                                                                                                                                                                                      +    if len(ids) == 0 {
                                                                                                                                                                                                      +        // 沒有此數字了
                                                                                                                                                                                                      +        delete(this.set, val)
                                                                                                                                                                                                      +    }
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +    this.arr = this.arr[:this.size-1]
                                                                                                                                                                                                      +    this.size--
                                                                                                                                                                                                      +    return true
                                                                                                                                                                                                      +}
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +func (this *RandomizedCollection) GetRandom() int {
                                                                                                                                                                                                      +    index := rand.Intn(this.size)
                                                                                                                                                                                                      +    return this.arr[index]
                                                                                                                                                                                                      +}
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +/**
                                                                                                                                                                                                      + * Your RandomizedCollection object will be instantiated and called as such:
                                                                                                                                                                                                      + * obj := Constructor();
                                                                                                                                                                                                      + * param_1 := obj.Insert(val);
                                                                                                                                                                                                      + * param_2 := obj.Remove(val);
                                                                                                                                                                                                      + * param_3 := obj.GetRandom();
                                                                                                                                                                                                      + */
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +

                                                                                                                                                                                                      Benchmark

                                                                                                                                                                                                      +
                                                                                                                                                                                                      
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      + +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      +
                                                                                                                                                                                                      + +

                                                                                                                                                                                                      results matching ""

                                                                                                                                                                                                      +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        + +

                                                                                                                                                                                                        No results matching ""

                                                                                                                                                                                                        + +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        + + + + + + +
                                                                                                                                                                                                        + + +
                                                                                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main.go b/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main.go new file mode 100644 index 000000000..6f76d3dee --- /dev/null +++ b/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main.go @@ -0,0 +1,79 @@ +package insertdeletegetrandomo1duplicatesallowed + +import ( + "math/rand" +) + +// ๆ™‚้–“่ค‡้›œ O(1), ็ฉบ้–“่ค‡้›œ O(n) +type RandomizedCollection struct { + arr []int + set map[int]map[int]struct{} + size int +} + +func Constructor() RandomizedCollection { + arr := make([]int, 0) + set := make(map[int]map[int]struct{}) + size := 0 + return RandomizedCollection{arr, set, size} +} + +func (this *RandomizedCollection) Insert(val int) bool { + ids, ok := this.set[val] + if !ok { + // ๆฒ’ๆœ‰ๆญคๆ•ธๅญ—ไบ†, ๅปบ็ซ‹ไธ€ๅ€‹index็š„map + ids = map[int]struct{}{} + this.set[val] = ids + } + // index็š„map, key็‚บ็•ถๅ‰ๆœ€ๅพŒ็š„index, value็‚บ็ฉบ็š„struct{}{} + ids[this.size] = struct{}{} + this.arr = append(this.arr, val) + this.size++ + return !ok +} + +func (this *RandomizedCollection) Remove(val int) bool { + ids, ok := this.set[val] + if !ok { + return false + } + + // ๆ‰พๅ‡บๆญคval็š„็š„index, ไธฆไธ”ๆŠŠๆœ€ๅพŒไธ€ๅ€‹index็š„mapๅˆช้™ค, ไธฆไธ”ๆŠŠๆญคindex็š„value่จญ็‚บ็ฉบ็š„struct{}{} + var i int + for id := range ids { + i = id + break + } + + // ๅฐ‡ๆœ€ๅพŒไธ€็ญ†็งปๅˆฐ่ฆๆ›ฟๆ›็š„id + this.arr[i] = this.arr[this.size-1] + delete(ids, i) + // ๅ› ็‚บๆŠŠๆœ€ๅพŒไธ€ๅ€‹ๅ…ƒ็ด ็งปๅˆฐๅ‰้ขไบ† + delete(this.set[this.arr[i]], this.size-1) + + if i < this.size-1 { + // fmt.Printf("i =%d, this.size =%d\t", i, this.size) + this.set[this.arr[i]][i] = struct{}{} + } + if len(ids) == 0 { + // ๆฒ’ๆœ‰ๆญคๆ•ธๅญ—ไบ† + delete(this.set, val) + } + + this.arr = this.arr[:this.size-1] + this.size-- + return true +} + +func (this *RandomizedCollection) GetRandom() int { + index := rand.Intn(this.size) + return this.arr[index] +} + +/** + * Your RandomizedCollection object will be instantiated and called as such: + * obj := Constructor(); + * param_1 := obj.Insert(val); + * param_2 := obj.Remove(val); + * param_3 := obj.GetRandom(); + */ diff --git a/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main_test.go b/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main_test.go new file mode 100644 index 000000000..07b243d25 --- /dev/null +++ b/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main_test.go @@ -0,0 +1,60 @@ +package insertdeletegetrandomo1duplicatesallowed + +import ( + "fmt" + "reflect" + "testing" +) + +var tests = []struct { + arg1 []string + arg2 []int + want []interface{} +}{ + { + []string{ + "RandomizedCollection", "insert", "insert", "insert", "remove", "getRandom", + }, + []int{ + 0, 1, 1, 2, 2, 1, + }, + []interface{}{ + nil, true, false, true, true, 1, + }, + }, + // { + // []string{ + // "RandomizedCollection", "insert", "insert", "insert", "getRandom", "remove", "getRandom", + // }, + // []int{ + // 0, 1, 1, 2, 0, 1, 0, + // }, + // []interface{}{ + // nil, true, false, true, 2, true, false, 2, + // }, + // }, +} + +func TestInsertdeletegetrandom(t *testing.T) { + for _, tt := range tests { + result := []interface{}{} + var rSet RandomizedCollection + for i := 0; i < len(tt.arg1); i++ { + switch tt.arg1[i] { + case "RandomizedCollection": + rSet = Constructor() + result = append(result, nil) + case "insert": + result = append(result, rSet.Insert(tt.arg2[i])) + case "remove": + result = append(result, rSet.Remove(tt.arg2[i])) + case "getRandom": + result = append(result, rSet.GetRandom()) + } + fmt.Println(rSet.set) + } + if !reflect.DeepEqual(result, tt.want) { + t.Errorf("got = %v, want = %v", result, tt.want) + } + } +} diff --git a/Leetcode/0409.Longest-Palindrome/index.html b/Leetcode/0409.Longest-Palindrome/index.html new file mode 100644 index 000000000..de5c723cd --- /dev/null +++ b/Leetcode/0409.Longest-Palindrome/index.html @@ -0,0 +1,3840 @@ + + + + + + + 0409. Longest Palindrome ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        + +

                                                                                                                                                                                                        409. Longest Palindrome

                                                                                                                                                                                                        題目

                                                                                                                                                                                                        +

                                                                                                                                                                                                        Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

                                                                                                                                                                                                        +

                                                                                                                                                                                                        Letters are case sensitive, for example, "Aa" is not considered a palindrome here.

                                                                                                                                                                                                        +

                                                                                                                                                                                                        Example 1:

                                                                                                                                                                                                        +
                                                                                                                                                                                                        Input: s = "abccccdd"
                                                                                                                                                                                                        +Output: 7
                                                                                                                                                                                                        +Explanation: One longest palindrome that can be built is "dccaccd", whose length is 7.
                                                                                                                                                                                                        +

                                                                                                                                                                                                        Example 2:

                                                                                                                                                                                                        +
                                                                                                                                                                                                        Input: s = "a"
                                                                                                                                                                                                        +Output: 1
                                                                                                                                                                                                        +Explanation: The longest palindrome that can be built is "a", whose length is 1.
                                                                                                                                                                                                        +

                                                                                                                                                                                                        Constraints:

                                                                                                                                                                                                        +
                                                                                                                                                                                                          +
                                                                                                                                                                                                        • 1 <= s.length <= 2000
                                                                                                                                                                                                        • +
                                                                                                                                                                                                        • s consists of lowercase and/or uppercase English letters only.
                                                                                                                                                                                                        • +
                                                                                                                                                                                                        +

                                                                                                                                                                                                        題目大意

                                                                                                                                                                                                        +

                                                                                                                                                                                                        給定一個包含大寫字母和小寫字母的字符串,找到通過這些字母構造成的最長的回文串。 +在構造過程中,請注意區分大小寫。比如 Aa 不能當做一個回文字符串。 +注意:假設字符串的長度不會超過 1010。

                                                                                                                                                                                                        +

                                                                                                                                                                                                        解題思路

                                                                                                                                                                                                        +
                                                                                                                                                                                                          +
                                                                                                                                                                                                        • 給出一個字符串,要求用這個字符串裡面的字符組成一個回文串,問回文串最多可以組合成多長的?
                                                                                                                                                                                                        • +
                                                                                                                                                                                                        • 這也是一道題水題,然後先統計每個字符的頻次,每個字符能取2個的取2個,不足2個的並且當前構造中的回文串是偶數的情況下(即每2個都陣容了),可以取1個。最後組合出來的就是終止回文串。
                                                                                                                                                                                                        • +
                                                                                                                                                                                                        +

                                                                                                                                                                                                        來源

                                                                                                                                                                                                        + +

                                                                                                                                                                                                        解答

                                                                                                                                                                                                        +
                                                                                                                                                                                                        package longestpalindrome
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +func LongestPalindrome(s string) int {
                                                                                                                                                                                                        +    counter := make(map[rune]int)
                                                                                                                                                                                                        +    for _, r := range s {
                                                                                                                                                                                                        +        counter[r]++
                                                                                                                                                                                                        +    }
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +    result := 0
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +    for _, v := range counter {
                                                                                                                                                                                                        +        result += v / 2 * 2
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +        // 字符出現奇數次,我們可以選擇其中一個, 放在回文串的中間,這可以貢獻一個長度
                                                                                                                                                                                                        +        if result%2 == 0 && v%2 == 1 {
                                                                                                                                                                                                        +            result++
                                                                                                                                                                                                        +        }
                                                                                                                                                                                                        +    }
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +    return result
                                                                                                                                                                                                        +}
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        + +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        +
                                                                                                                                                                                                        + +

                                                                                                                                                                                                        results matching ""

                                                                                                                                                                                                        +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          + +

                                                                                                                                                                                                          No results matching ""

                                                                                                                                                                                                          + +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          + + + + + + +
                                                                                                                                                                                                          + + +
                                                                                                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0409.Longest-Palindrome/main.go b/Leetcode/0409.Longest-Palindrome/main.go new file mode 100644 index 000000000..ea85fca9a --- /dev/null +++ b/Leetcode/0409.Longest-Palindrome/main.go @@ -0,0 +1,21 @@ +package longestpalindrome + +func LongestPalindrome(s string) int { + counter := make(map[rune]int) + for _, r := range s { + counter[r]++ + } + + result := 0 + + for _, v := range counter { + result += v / 2 * 2 + + // ๅญ—็ฌฆๅ‡บ็พๅฅ‡ๆ•ธๆฌก๏ผŒๆˆ‘ๅ€‘ๅฏไปฅ้ธๆ“‡ๅ…ถไธญไธ€ๅ€‹, ๆ”พๅœจๅ›žๆ–‡ไธฒ็š„ไธญ้–“๏ผŒ้€™ๅฏไปฅ่ฒข็ปไธ€ๅ€‹้•ทๅบฆ + if result%2 == 0 && v%2 == 1 { + result++ + } + } + + return result +} diff --git a/Leetcode/0409.Longest-Palindrome/main_test.go b/Leetcode/0409.Longest-Palindrome/main_test.go new file mode 100644 index 000000000..80a30b19f --- /dev/null +++ b/Leetcode/0409.Longest-Palindrome/main_test.go @@ -0,0 +1,37 @@ +package longestpalindrome + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "abccccdd", + 7, + }, + { + "a", + 1, + }, +} + +func TestLongestPalindrome(t *testing.T) { + for _, tt := range tests { + if got := LongestPalindrome(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindrome(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindrome(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0412.Fizz-Buzz/index.html b/Leetcode/0412.Fizz-Buzz/index.html new file mode 100644 index 000000000..d1f59b047 --- /dev/null +++ b/Leetcode/0412.Fizz-Buzz/index.html @@ -0,0 +1,3837 @@ + + + + + + + 412. Fizz Buzz ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          + +

                                                                                                                                                                                                          412. Fizz Buzz

                                                                                                                                                                                                          題目

                                                                                                                                                                                                          +

                                                                                                                                                                                                          Facebook, Microsoft, Apple +Given an integer n, return a string array answer (1-indexed) where:

                                                                                                                                                                                                          +

                                                                                                                                                                                                          answer[i] == "FizzBuzz" if i is divisible by 3 and 5. +answer[i] == "Fizz" if i is divisible by 3. +answer[i] == "Buzz" if i is divisible by 5. +answer[i] == i (as a string) if none of the above conditions are true.

                                                                                                                                                                                                          +

                                                                                                                                                                                                          Example 1:

                                                                                                                                                                                                          +

                                                                                                                                                                                                          Input: n = 3 +Output: ["1","2","Fizz"] +Example 2:

                                                                                                                                                                                                          +

                                                                                                                                                                                                          Input: n = 5 +Output: ["1","2","Fizz","4","Buzz"] +Example 3:

                                                                                                                                                                                                          +

                                                                                                                                                                                                          Input: n = 15 +Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

                                                                                                                                                                                                          +

                                                                                                                                                                                                          Constraints:

                                                                                                                                                                                                          +

                                                                                                                                                                                                          1 <= n <= 104

                                                                                                                                                                                                          +

                                                                                                                                                                                                          題目大意

                                                                                                                                                                                                          +

                                                                                                                                                                                                          解題思路

                                                                                                                                                                                                          +

                                                                                                                                                                                                          Big O

                                                                                                                                                                                                          +

                                                                                                                                                                                                          時間複雜 : O(n) +空間複雜 : O(n)

                                                                                                                                                                                                          +

                                                                                                                                                                                                          來源

                                                                                                                                                                                                          + +

                                                                                                                                                                                                          解答

                                                                                                                                                                                                          +

                                                                                                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0412.Fizz-Buzz/main.go

                                                                                                                                                                                                          +
                                                                                                                                                                                                          package fizzbuzz
                                                                                                                                                                                                          +
                                                                                                                                                                                                          +import "strconv"
                                                                                                                                                                                                          +
                                                                                                                                                                                                          +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                                                                          +func fizzBuzz(n int) []string {
                                                                                                                                                                                                          +    var result []string
                                                                                                                                                                                                          +    for i := 1; i 
                                                                                                                                                                                                          +

                                                                                                                                                                                                          Benchmark

                                                                                                                                                                                                          +
                                                                                                                                                                                                          goos: darwin
                                                                                                                                                                                                          +goarch: amd64
                                                                                                                                                                                                          +pkg: LeetcodeGolang/Leetcode/0412.Fizz-Buzz
                                                                                                                                                                                                          +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
                                                                                                                                                                                                          +BenchmarkFizzBuzz-4      5918809               287.1 ns/op           112 B/op          3 allocs/op
                                                                                                                                                                                                          +BenchmarkFizzBuzz2-4     5024536               223.8 ns/op           112 B/op          3 allocs/op
                                                                                                                                                                                                          +BenchmarkFizzBuzz3-4     5406643               196.3 ns/op           112 B/op          3 allocs/op
                                                                                                                                                                                                          +PASS
                                                                                                                                                                                                          +ok      LeetcodeGolang/Leetcode/0412.Fizz-Buzz  5.507s
                                                                                                                                                                                                          +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          + +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          +
                                                                                                                                                                                                          + +

                                                                                                                                                                                                          results matching ""

                                                                                                                                                                                                          +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            + +

                                                                                                                                                                                                            No results matching ""

                                                                                                                                                                                                            + +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            + + + + + + +
                                                                                                                                                                                                            + + +
                                                                                                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0412.Fizz-Buzz/main.go b/Leetcode/0412.Fizz-Buzz/main.go new file mode 100644 index 000000000..546e09b11 --- /dev/null +++ b/Leetcode/0412.Fizz-Buzz/main.go @@ -0,0 +1,63 @@ +package fizzbuzz + +import "strconv" + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +func fizzBuzz(n int) []string { + var result []string + for i := 1; i <= n; i++ { + if i%15 == 0 { + result = append(result, "FizzBuzz") + } else if i%3 == 0 { + result = append(result, "Fizz") + } else if i%5 == 0 { + result = append(result, "Buzz") + } else { + result = append(result, strconv.Itoa(i)) + } + } + return result +} + +func fizzBuzz2(n int) []string { + var result []string + for i := 1; i <= n; i++ { + var str string + if i%3 == 0 { + str += "Fizz" + } + if i%5 == 0 { + str += "Buzz" + } + if len(str) <= 0 { + str = strconv.Itoa(i) + } + result = append(result, str) + } + return result +} + +// ๆœ€ไฝณ +func fizzBuzz3(n int) []string { + var result []string + fizz := 0 + buzz := 0 + for i := 1; i <= n; i++ { + fizz++ + buzz++ + if fizz == 3 && buzz == 5 { + result = append(result, "FizzBuzz") + fizz = 0 + buzz = 0 + } else if fizz == 3 { + result = append(result, "Fizz") + fizz = 0 + } else if buzz == 5 { + result = append(result, "Buzz") + buzz = 0 + } else { + result = append(result, strconv.Itoa(i)) + } + } + return result +} diff --git a/Leetcode/0412.Fizz-Buzz/main_test.go b/Leetcode/0412.Fizz-Buzz/main_test.go new file mode 100644 index 000000000..956318e6e --- /dev/null +++ b/Leetcode/0412.Fizz-Buzz/main_test.go @@ -0,0 +1,69 @@ +package fizzbuzz + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 int + want []string +}{ + { + 3, + []string{"1", "2", "Fizz"}, + }, +} + +func TestFizzBuzz(t *testing.T) { + for _, tt := range tests { + if got := fizzBuzz(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // if got := fizzBuzz(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkFizzBuzz(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + fizzBuzz(tests[0].arg1) + } +} + +func TestFizzBuzz2(t *testing.T) { + for _, tt := range tests { + if got := fizzBuzz2(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // if got := fizzBuzz2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkFizzBuzz2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + fizzBuzz2(tests[0].arg1) + } +} + +func TestFizzBuzz3(t *testing.T) { + for _, tt := range tests { + if got := fizzBuzz3(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // if got := fizzBuzz3(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkFizzBuzz3(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + fizzBuzz3(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0412.Fizz-Buzz -bench=. + +*/ diff --git a/Leetcode/0438.Find-All-Anagrams-in-a-String/index.html b/Leetcode/0438.Find-All-Anagrams-in-a-String/index.html new file mode 100644 index 000000000..d9b5317d4 --- /dev/null +++ b/Leetcode/0438.Find-All-Anagrams-in-a-String/index.html @@ -0,0 +1,3894 @@ + + + + + + + 0438.Find All Anagrams in a String ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            + +

                                                                                                                                                                                                            438. Find All Anagrams in a String

                                                                                                                                                                                                            题目

                                                                                                                                                                                                            +

                                                                                                                                                                                                            Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

                                                                                                                                                                                                            +

                                                                                                                                                                                                            An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

                                                                                                                                                                                                            +

                                                                                                                                                                                                            Example 1:

                                                                                                                                                                                                            +
                                                                                                                                                                                                            Input: s = "cbaebabacd", p = "abc"
                                                                                                                                                                                                            +Output: [0,6]
                                                                                                                                                                                                            +Explanation:
                                                                                                                                                                                                            +The substring with start index = 0 is "cba", which is an anagram of "abc".
                                                                                                                                                                                                            +The substring with start index = 6 is "bac", which is an anagram of "abc".
                                                                                                                                                                                                            +

                                                                                                                                                                                                            Example 2:

                                                                                                                                                                                                            +
                                                                                                                                                                                                            Input: s = "abab", p = "ab"
                                                                                                                                                                                                            +Output: [0,1,2]
                                                                                                                                                                                                            +Explanation:
                                                                                                                                                                                                            +The substring with start index = 0 is "ab", which is an anagram of "ab".
                                                                                                                                                                                                            +The substring with start index = 1 is "ba", which is an anagram of "ab".
                                                                                                                                                                                                            +The substring with start index = 2 is "ab", which is an anagram of "ab".
                                                                                                                                                                                                            +

                                                                                                                                                                                                            Constraints:

                                                                                                                                                                                                            +

                                                                                                                                                                                                            1 <= s.length, p.length <= 3 * 104 +s and p consist of lowercase English letters.

                                                                                                                                                                                                            +

                                                                                                                                                                                                            題目大意

                                                                                                                                                                                                            +

                                                                                                                                                                                                            找所有字母異位詞, 就像全排列 +給定一個字符串 S 和非空的字符串 P, 找到 S 中所有是 P 得排列, 並返回他的起始 index

                                                                                                                                                                                                            +

                                                                                                                                                                                                            解題思路

                                                                                                                                                                                                            +

                                                                                                                                                                                                            0567.Permutation-in-String類似, 只是把找到的答案記錄起來

                                                                                                                                                                                                            +

                                                                                                                                                                                                            來源

                                                                                                                                                                                                            + +
                                                                                                                                                                                                            package findallanagramsinastring
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +func FindAnagrams(s string, p string) []int {
                                                                                                                                                                                                            +    need, window := make(map[rune]int), make(map[rune]int)
                                                                                                                                                                                                            +    for _, c := range p {
                                                                                                                                                                                                            +        need[c]++
                                                                                                                                                                                                            +    }
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +    left, right := 0, 0
                                                                                                                                                                                                            +    valid := 0
                                                                                                                                                                                                            +    res := []int{} //紀錄結果
                                                                                                                                                                                                            +    for right < len(s) {
                                                                                                                                                                                                            +        c := rune(s[right])
                                                                                                                                                                                                            +        right++
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +        if need[c] > 0 {
                                                                                                                                                                                                            +            window[c]++
                                                                                                                                                                                                            +            if window[c] == need[c] {
                                                                                                                                                                                                            +                valid++
                                                                                                                                                                                                            +            }
                                                                                                                                                                                                            +        }
                                                                                                                                                                                                            +        // fmt.Printf("[%d,%d) \n", left, right)
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +        // 判斷左視窗是否收縮, 看看視窗長度是否同要找的字串的長度
                                                                                                                                                                                                            +        if (right - left) >= len(p) {
                                                                                                                                                                                                            +            if valid == len(need) {
                                                                                                                                                                                                            +                // 想要的字元都找到了, 紀錄index
                                                                                                                                                                                                            +                res = append(res, left)
                                                                                                                                                                                                            +            }
                                                                                                                                                                                                            +            d := rune(s[left])
                                                                                                                                                                                                            +            left++
                                                                                                                                                                                                            +            if need[d] > 0 {
                                                                                                                                                                                                            +                if window[d] == need[d] {
                                                                                                                                                                                                            +                    valid--
                                                                                                                                                                                                            +                }
                                                                                                                                                                                                            +                window[d]--
                                                                                                                                                                                                            +            }
                                                                                                                                                                                                            +        }
                                                                                                                                                                                                            +    }
                                                                                                                                                                                                            +    return res
                                                                                                                                                                                                            +}
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +// 用 slice 取代 map 來優化
                                                                                                                                                                                                            +func FindAnagramsSlice(s string, p string) []int {
                                                                                                                                                                                                            +    need := [256]int{}
                                                                                                                                                                                                            +    for _, c := range p {
                                                                                                                                                                                                            +        need[c-'a']++
                                                                                                                                                                                                            +    }
                                                                                                                                                                                                            +    left, right := 0, 0
                                                                                                                                                                                                            +    count := len(p)
                                                                                                                                                                                                            +    res := []int{}
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +    for right < len(s) {
                                                                                                                                                                                                            +        c := s[right] - 'a'
                                                                                                                                                                                                            +        if need[c] > 0 {
                                                                                                                                                                                                            +            count--
                                                                                                                                                                                                            +        }
                                                                                                                                                                                                            +        need[c]--
                                                                                                                                                                                                            +        right++
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +        if count == 0 {
                                                                                                                                                                                                            +            res = append(res, left)
                                                                                                                                                                                                            +        }
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +        if (right - left) >= len(p) {
                                                                                                                                                                                                            +            d := s[left] - 'a'
                                                                                                                                                                                                            +            if need[d] >= 0 {
                                                                                                                                                                                                            +                count++
                                                                                                                                                                                                            +            }
                                                                                                                                                                                                            +            need[d]++
                                                                                                                                                                                                            +            left++
                                                                                                                                                                                                            +        }
                                                                                                                                                                                                            +    }
                                                                                                                                                                                                            +    return res
                                                                                                                                                                                                            +}
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            + +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            +
                                                                                                                                                                                                            + +

                                                                                                                                                                                                            results matching ""

                                                                                                                                                                                                            +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              + +

                                                                                                                                                                                                              No results matching ""

                                                                                                                                                                                                              + +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              + + + + + + +
                                                                                                                                                                                                              + + +
                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0438.Find-All-Anagrams-in-a-String/main.go b/Leetcode/0438.Find-All-Anagrams-in-a-String/main.go new file mode 100644 index 000000000..e61267280 --- /dev/null +++ b/Leetcode/0438.Find-All-Anagrams-in-a-String/main.go @@ -0,0 +1,75 @@ +package findallanagramsinastring + +func FindAnagrams(s string, p string) []int { + need, window := make(map[rune]int), make(map[rune]int) + for _, c := range p { + need[c]++ + } + + left, right := 0, 0 + valid := 0 + res := []int{} //็ด€้Œ„็ตๆžœ + for right < len(s) { + c := rune(s[right]) + right++ + + if need[c] > 0 { + window[c]++ + if window[c] == need[c] { + valid++ + } + } + // fmt.Printf("[%d,%d) \n", left, right) + + // ๅˆคๆ–ทๅทฆ่ฆ–็ช—ๆ˜ฏๅฆๆ”ถ็ธฎ, ็œ‹็œ‹่ฆ–็ช—้•ทๅบฆๆ˜ฏๅฆๅŒ่ฆๆ‰พ็š„ๅญ—ไธฒ็š„้•ทๅบฆ + if (right - left) >= len(p) { + if valid == len(need) { + // ๆƒณ่ฆ็š„ๅญ—ๅ…ƒ้ƒฝๆ‰พๅˆฐไบ†, ็ด€้Œ„index + res = append(res, left) + } + d := rune(s[left]) + left++ + if need[d] > 0 { + if window[d] == need[d] { + valid-- + } + window[d]-- + } + } + } + return res +} + +// ็”จ slice ๅ–ไปฃ map ไพ†ๅ„ชๅŒ– +func FindAnagramsSlice(s string, p string) []int { + need := [256]int{} + for _, c := range p { + need[c-'a']++ + } + left, right := 0, 0 + count := len(p) + res := []int{} + + for right < len(s) { + c := s[right] - 'a' + if need[c] > 0 { + count-- + } + need[c]-- + right++ + + if count == 0 { + res = append(res, left) + } + + if (right - left) >= len(p) { + d := s[left] - 'a' + if need[d] >= 0 { + count++ + } + need[d]++ + left++ + } + } + return res +} diff --git a/Leetcode/0438.Find-All-Anagrams-in-a-String/main_test.go b/Leetcode/0438.Find-All-Anagrams-in-a-String/main_test.go new file mode 100644 index 000000000..3c64d506a --- /dev/null +++ b/Leetcode/0438.Find-All-Anagrams-in-a-String/main_test.go @@ -0,0 +1,65 @@ +package findallanagramsinastring + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 string + arg2 string + want []int +}{ + { + "cbaebabacd", + "abc", + []int{0, 6}, + }, + { + "abab", + "ab", + []int{0, 1, 2}, + }, +} + +func TestFindAnagrams(t *testing.T) { + for _, tt := range tests { + if got := FindAnagrams(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestFindAnagramsSlice(t *testing.T) { + for _, tt := range tests { + if got := FindAnagramsSlice(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkFindAnagrams(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FindAnagrams(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkFindAnagramsSlice(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FindAnagramsSlice(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0438.Find-All-Anagrams-in-a-String -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0438.Find-All-Anagrams-in-a-String +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkFindAnagrams-8 1572444 690.4 ns/op 24 B/op 2 allocs/op +BenchmarkFindAnagramsSlice-8 11687409 136.9 ns/op 24 B/op 2 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0438.Find-All-Anagrams-in-a-String 4.329s +*/ diff --git a/Leetcode/0509.Fibonacci-Number/Fibonacci-Number.go b/Leetcode/0509.Fibonacci-Number/Fibonacci-Number.go new file mode 100644 index 000000000..fd702c247 --- /dev/null +++ b/Leetcode/0509.Fibonacci-Number/Fibonacci-Number.go @@ -0,0 +1,182 @@ +// --- Directions +// Print out the n-th entry in the fibonacci series. +// The fibonacci series is an ordering of numbers where +// each number is the sum of the preceeding two. +// For example, the sequence +// [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] +// forms the first ten entries of the fibonacci series. +// Example: +// fib(4) === 3 + +package fibonaccinumber + +import "math" + +// Fib : iterative ่ฟดๅœˆ O(n) . ็ฉบ้–“่ค‡้›œ O(n). ่‡ชๅบ•ๅ‘ไธŠ็š„่จ˜ๆ†ถๅŒ–ๆœ็ดข +func FibIterative(n int) int { + var result = []int{0, 1} + + for i := 2; i <= n; i++ { + a := result[i-1] + b := result[i-2] + result = append(result, a+b) + } + return result[n] +} + +// Fibrecur : recursive ้ž่ฟด O(2^n) . ็ฉบ้–“่ค‡้›œ O(n) +func Fibrecur(n int) int { + if n < 2 { + return n + } + + return Fibrecur(n-1) + Fibrecur(n-2) +} + +// the memo table +var memo = map[int]int{} + +// FibDP : memoization ๅ‚™ๅฟ˜้Œ„็š„้ž่ฟด +// ๆฏ”่ผƒๅฟซ! +func FibDP(n int) int { + // ๅฆ‚ๆžœๆœ‰cached ็›ดๆŽฅๅ›žๅ‚ณ + if v, vok := memo[n]; vok == true { + // cached + return v + } + + if _, vok := memo[0]; vok == false { + // ๆฒ’cache + memo[0] = 0 + } + + if _, vok := memo[1]; vok == false { + // ๆฒ’cache + memo[1] = 1 + } + + for i := 2; i <= n; i++ { + if _, vok := memo[i]; vok == false { + // ๆฒ’cache + a := memo[i-1] + b := memo[i-2] + memo[i] = a + b + } + // fmt.Println(memo) + } + return memo[n] + // return FibDP(n-1) + FibDP(n-2) +} + +// ็‹€ๆ…‹ๅฃ“็ธฎ +func FibDPStateCompression(n int) int { + if n == 0 { + return 0 + } + if n == 2 || n == 1 { + return 1 + } + + prev := 1 + curr := 1 + + for i := 3; i <= n; i++ { + sum := prev + curr + prev = curr + curr = sum + } + return curr +} + +var cache = map[int]int{} + +func memoize(fn func(int) int) func(int) int { + return func(args int) int { + if _, vok := cache[args]; vok == true { + return cache[args] + } + + result := fn(args) // ่ท‘ Fibrecur(args) + cache[args] = result + return result + } +} + +// Fibmem : memoization ๆ‹‰ๅ‡บ้ž่ฟดfunction +func Fibmem(n int) int { + result := memoize(Fibrecur) + return result(n) +} + +// ่งฃๆณ•ไบ” ็Ÿฉ้˜ตๅฟซ้€Ÿๅน‚ ๆ—ถ้—ดๅคๆ‚ๅบฆ O(log n)๏ผŒ็ฉบ้—ดๅคๆ‚ๅบฆ O(log n) +// | 1 1 | ^ n = | F(n+1) F(n) | +// | 1 0 | | F(n) F(n-1) | +func Fib5(N int) int { + if N <= 1 { + return N + } + var A = [2][2]int{ + {1, 1}, + {1, 0}, + } + A = matrixPower(A, N-1) + return A[0][0] +} + +func matrixPower(A [2][2]int, N int) [2][2]int { + if N <= 1 { + return A + } + A = matrixPower(A, N/2) + A = multiply(A, A) + + var B = [2][2]int{ + {1, 1}, + {1, 0}, + } + if N%2 != 0 { + A = multiply(A, B) + } + + return A +} + +func multiply(A [2][2]int, B [2][2]int) [2][2]int { + x := A[0][0]*B[0][0] + A[0][1]*B[1][0] + y := A[0][0]*B[0][1] + A[0][1]*B[1][1] + z := A[1][0]*B[0][0] + A[1][1]*B[1][0] + w := A[1][0]*B[0][1] + A[1][1]*B[1][1] + A[0][0] = x + A[0][1] = y + A[1][0] = z + A[1][1] = w + return A +} + +// ่งฃๆณ•ๅ…ญ ๅ…ฌๅผๆณ• f(n)=(1/โˆš5)*{[(1+โˆš5)/2]^n -[(1-โˆš5)/2]^n}๏ผŒ็”จ ๆ—ถ้—ดๅคๆ‚ๅบฆๅœจ O(log n) ๅ’Œ O(n) ไน‹้—ด๏ผŒ็ฉบ้—ดๅคๆ‚ๅบฆ O(1) +// ็ป่ฟ‡ๅฎž้™…ๆต‹่ฏ•๏ผŒไผšๅ‘็Žฐ pow() ็ณป็ปŸๅ‡ฝๆ•ฐๆฏ”ๅฟซ้€Ÿๅน‚ๆ…ข๏ผŒ่ฏดๆ˜Ž pow() ๆฏ” O(log n) ๆ…ข +// ๆ–ๆณข้‚ฃๅฅ‘ๆ•ฐๅˆ—ๆ˜ฏไธ€ไธช่‡ช็„ถๆ•ฐ็š„ๆ•ฐๅˆ—๏ผŒ้€š้กนๅ…ฌๅผๅดๆ˜ฏ็”จๆ— ็†ๆ•ฐๆฅ่กจ่พพ็š„ใ€‚่€Œไธ”ๅฝ“ n ่ถ‹ๅ‘ไบŽๆ— ็ฉทๅคงๆ—ถ๏ผŒๅ‰ไธ€้กนไธŽๅŽไธ€้กน็š„ๆฏ”ๅ€ผ่ถŠๆฅ่ถŠ้€ผ่ฟ‘้ป„้‡‘ๅˆ†ๅ‰ฒ 0.618๏ผˆๆˆ–่€…่ฏดๅŽไธ€้กนไธŽๅ‰ไธ€้กน็š„ๆฏ”ๅ€ผๅฐๆ•ฐ้ƒจๅˆ†่ถŠๆฅ่ถŠ้€ผ่ฟ‘ 0.618๏ผ‰ใ€‚ +// ๆ–ๆณข้‚ฃๅฅ‘ๆ•ฐๅˆ—็”จ่ฎก็ฎ—ๆœบ่ฎก็ฎ—็š„ๆ—ถๅ€™ๅฏไปฅ็›ดๆŽฅ็”จๅ››่ˆไบ”ๅ…ฅๅ‡ฝๆ•ฐ Round ๆฅ่ฎก็ฎ—ใ€‚ +func Fib6(N int) int { + var goldenRatio float64 = float64((1 + math.Sqrt(5)) / 2) + return int(math.Round(math.Pow(goldenRatio, float64(N)) / math.Sqrt(5))) +} + +// ่งฃๆณ•ไธƒ ๅ”็จ‹็‰ˆ๏ผŒไฝ†ๆ˜ฏๆ—ถ้—ด็‰นๅˆซๆ…ข๏ผŒไธๆŽจ่๏ผŒๆ”พๅœจ่ฟ™้‡Œๅชๆ˜ฏๅ‘Š่ฏ‰ๅคงๅฎถ๏ผŒๅ†™ LeetCode ็ฎ—ๆณ•้ข˜็š„ๆ—ถๅ€™๏ผŒๅฏๅŠจ goroutine ็‰นๅˆซๆ…ข +func Fib7(N int) int { + return <-fibb(N) +} + +func fibb(n int) <-chan int { + result := make(chan int) + go func() { + defer close(result) + + if n <= 1 { + result <- n + return + } + result <- <-fibb(n-1) + <-fibb(n-2) + }() + return result +} diff --git a/Leetcode/0509.Fibonacci-Number/Fibonacci-Number_test.go b/Leetcode/0509.Fibonacci-Number/Fibonacci-Number_test.go new file mode 100644 index 000000000..d3e676efd --- /dev/null +++ b/Leetcode/0509.Fibonacci-Number/Fibonacci-Number_test.go @@ -0,0 +1,236 @@ +package fibonaccinumber + +import ( + "testing" +) + +func TestFib(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "FibIterative", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := FibIterative(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestFibrecur(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "Fibrecur", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Fibrecur(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestFibDP(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "FibDP", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := FibDP(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestFibDPStateCompression(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "FibDPStateCompression", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := FibDPStateCompression(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestFibmem(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "Fibmem", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Fibmem(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestFib5(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "Fib5", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Fib5(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestFib6(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "ๅ…ฌๅผๆณ•", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Fib6(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func TestFib7(t *testing.T) { + tests := []struct { + name string + in int + want int + }{ + { + name: "ๅ”็จ‹็‰ˆ", + in: 39, + want: 63245986, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Fib7(tt.in); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + }) + } +} + +func BenchmarkFib(b *testing.B) { + input := 39 + b.ResetTimer() + for i := 0; i < b.N; i++ { + FibIterative(input) + } +} + +func BenchmarkFibrecur(b *testing.B) { + input := 39 + b.ResetTimer() + for i := 0; i < b.N; i++ { + Fibrecur(input) + } +} + +func BenchmarkFibmem(b *testing.B) { + input := 39 + b.ResetTimer() + for i := 0; i < b.N; i++ { + Fibmem(input) + } +} + +func BenchmarkFibDP(b *testing.B) { + input := 39 + b.ResetTimer() + for i := 0; i < b.N; i++ { + FibDP(input) + } +} + +func BenchmarkFibDPStateCompression(b *testing.B) { + input := 39 + b.ResetTimer() + for i := 0; i < b.N; i++ { + FibDPStateCompression(input) + } +} + +// go test -benchmem -run=none MyGoNote/algorithms/Fibonacci -bench=. +/* +goos: darwin +goarch: amd64 +pkg: MyGoNote/algorithms/Fibonacci +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkFib-8 3409812 435.8 ns/op 992 B/op 5 allocs/op +BenchmarkFibrecur-8 3 391624567 ns/op 0 B/op 0 allocs/op +BenchmarkFibmem-8 106473912 11.56 ns/op 0 B/op 0 allocs/op +BenchmarkFibmem2-8 28739854 49.79 ns/op 16 B/op 1 allocs/op +BenchmarkFibmemStateCompression-8 123085564 10.72 ns/op 0 B/op 0 allocs/op +PASS +ok MyGoNote/algorithms/Fibonacci 12.090s +*/ diff --git a/Leetcode/0509.Fibonacci-Number/index.html b/Leetcode/0509.Fibonacci-Number/index.html new file mode 100644 index 000000000..4d9b9de7b --- /dev/null +++ b/Leetcode/0509.Fibonacci-Number/index.html @@ -0,0 +1,3851 @@ + + + + + + + 0509.Fibonacci Number ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              + +

                                                                                                                                                                                                              509. Fibonacci Number

                                                                                                                                                                                                              題目

                                                                                                                                                                                                              +

                                                                                                                                                                                                              The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

                                                                                                                                                                                                              +
                                                                                                                                                                                                              F(0) = 0, F(1) = 1
                                                                                                                                                                                                              +F(n) = F(n - 1) + F(n - 2), for n > 1.
                                                                                                                                                                                                              +

                                                                                                                                                                                                              Given n, calculate F(n).

                                                                                                                                                                                                              +

                                                                                                                                                                                                              Example 1:

                                                                                                                                                                                                              +
                                                                                                                                                                                                              Input: n = 2
                                                                                                                                                                                                              +Output: 1
                                                                                                                                                                                                              +Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
                                                                                                                                                                                                              +

                                                                                                                                                                                                              Example 2:

                                                                                                                                                                                                              +
                                                                                                                                                                                                              Input: n = 3
                                                                                                                                                                                                              +Output: 2
                                                                                                                                                                                                              +Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
                                                                                                                                                                                                              +

                                                                                                                                                                                                              Example 3:

                                                                                                                                                                                                              +
                                                                                                                                                                                                              Input: n = 4
                                                                                                                                                                                                              +Output: 3
                                                                                                                                                                                                              +Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
                                                                                                                                                                                                              +

                                                                                                                                                                                                              Constraints:

                                                                                                                                                                                                              +
                                                                                                                                                                                                                +
                                                                                                                                                                                                              • 0 <= n <= 30
                                                                                                                                                                                                              • +
                                                                                                                                                                                                              +

                                                                                                                                                                                                              題目大意

                                                                                                                                                                                                              +

                                                                                                                                                                                                              斐波那契數列, 通常用 F(n) 表示

                                                                                                                                                                                                              +

                                                                                                                                                                                                              F(0) = 0, F(1) = 1 +F(N) = F(N - 1) + F(N - 2), 其中 N > 1. +給定 N,計算 F(N)。

                                                                                                                                                                                                              +

                                                                                                                                                                                                              提示:0 ≤ N ≤ 30 +0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 ,610, 987……

                                                                                                                                                                                                              +

                                                                                                                                                                                                              解題思路

                                                                                                                                                                                                              +

                                                                                                                                                                                                              遇到遞迴最好畫出遞迴樹

                                                                                                                                                                                                              +
                                                                                                                                                                                                                          f(20)
                                                                                                                                                                                                              +           /     \ 
                                                                                                                                                                                                              +        f(19)   f(18)
                                                                                                                                                                                                              +       ...           ...
                                                                                                                                                                                                              +      /  \           /  \   
                                                                                                                                                                                                              +    f(1) f(2)       f(1) f(2)
                                                                                                                                                                                                              +

                                                                                                                                                                                                              這一題解法很多,大的分類是四種,遞歸,記憶化搜索(dp),矩陣快速冪,通項公式。其中記憶化搜索可以寫 3 種方法,自底向上的,自頂向下的,優化空間複雜度版的。通項公式方法實質是求 a^b 這個還可以用快速冪優化時間複雜度到 O(log n) 。

                                                                                                                                                                                                              +

                                                                                                                                                                                                              來源

                                                                                                                                                                                                              + +

                                                                                                                                                                                                              解答

                                                                                                                                                                                                              +

                                                                                                                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0509.Fibonacci-Number/Fibonacci-Number.go

                                                                                                                                                                                                              +
                                                                                                                                                                                                              // --- Directions
                                                                                                                                                                                                              +// Print out the n-th entry in the fibonacci series.
                                                                                                                                                                                                              +// The fibonacci series is an ordering of numbers where
                                                                                                                                                                                                              +// each number is the sum of the preceeding two.
                                                                                                                                                                                                              +// For example, the sequence
                                                                                                                                                                                                              +//  [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
                                                                                                                                                                                                              +// forms the first ten entries of the fibonacci series.
                                                                                                                                                                                                              +// Example:
                                                                                                                                                                                                              +//   fib(4) === 3
                                                                                                                                                                                                              +
                                                                                                                                                                                                              +package fibonaccinumber
                                                                                                                                                                                                              +
                                                                                                                                                                                                              +import "math"
                                                                                                                                                                                                              +
                                                                                                                                                                                                              +// Fib : iterative 迴圈  O(n) . 空間複雜  O(n). 自底向上的記憶化搜索
                                                                                                                                                                                                              +func FibIterative(n int) int {
                                                                                                                                                                                                              +    var result = []int{0, 1}
                                                                                                                                                                                                              +
                                                                                                                                                                                                              +    for i := 2; i 
                                                                                                                                                                                                              +
                                                                                                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              + +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              +
                                                                                                                                                                                                              + +

                                                                                                                                                                                                              results matching ""

                                                                                                                                                                                                              +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                + +

                                                                                                                                                                                                                No results matching ""

                                                                                                                                                                                                                + +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                + + + + + + +
                                                                                                                                                                                                                + + +
                                                                                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0516.Longest-Palindromic-Subsequence/index.html b/Leetcode/0516.Longest-Palindromic-Subsequence/index.html new file mode 100644 index 000000000..2c6998774 --- /dev/null +++ b/Leetcode/0516.Longest-Palindromic-Subsequence/index.html @@ -0,0 +1,3812 @@ + + + + + + + 516. Longest Palindromic Subsequence ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                + +

                                                                                                                                                                                                                516. Longest Palindromic Subsequence

                                                                                                                                                                                                                題目

                                                                                                                                                                                                                +

                                                                                                                                                                                                                Given a string s, find the longest palindromic subsequence's length in s.

                                                                                                                                                                                                                +

                                                                                                                                                                                                                A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

                                                                                                                                                                                                                +

                                                                                                                                                                                                                Example 1:

                                                                                                                                                                                                                +
                                                                                                                                                                                                                Input: s = "bbbab"
                                                                                                                                                                                                                +Output: 4
                                                                                                                                                                                                                +Explanation: One possible longest palindromic subsequence is "bbbb".
                                                                                                                                                                                                                +

                                                                                                                                                                                                                Example 2:

                                                                                                                                                                                                                +
                                                                                                                                                                                                                Input: s = "cbbd"
                                                                                                                                                                                                                +Output: 2
                                                                                                                                                                                                                +Explanation: One possible longest palindromic subsequence is "bb".
                                                                                                                                                                                                                +

                                                                                                                                                                                                                Constraints:

                                                                                                                                                                                                                +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                • 1 <= s.length <= 1000
                                                                                                                                                                                                                • +
                                                                                                                                                                                                                • s consists only of lowercase English letters.
                                                                                                                                                                                                                • +
                                                                                                                                                                                                                +

                                                                                                                                                                                                                題目大意

                                                                                                                                                                                                                +

                                                                                                                                                                                                                給你一個字符串 s,找到 s 中最長的回文子串。

                                                                                                                                                                                                                +

                                                                                                                                                                                                                解題思路

                                                                                                                                                                                                                +

                                                                                                                                                                                                                來源

                                                                                                                                                                                                                + +

                                                                                                                                                                                                                解答

                                                                                                                                                                                                                +
                                                                                                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                + +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                +
                                                                                                                                                                                                                + +

                                                                                                                                                                                                                results matching ""

                                                                                                                                                                                                                +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                  No results matching ""

                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  + + + + + + +
                                                                                                                                                                                                                  + + +
                                                                                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0516.Longest-Palindromic-Subsequence/main.go b/Leetcode/0516.Longest-Palindromic-Subsequence/main.go new file mode 100644 index 000000000..4b3184036 --- /dev/null +++ b/Leetcode/0516.Longest-Palindromic-Subsequence/main.go @@ -0,0 +1,50 @@ +package longestpalindromicsubsequence + +/* +* +dp:ๆ–น็จ‹่กจ็คบๅพžiๅˆฐj็š„้•ทๅบฆไธญ๏ผŒๅ›žๆ–‡ๅญไธฒ็š„้•ทๅบฆ +Base case: +a ->dp[i][i]=1 +case 1:s[i]==s[j] + + a*****a ->dp[i][j]=dp[i+1][j-1]+2 + +case 2:s[i]!=s[j] + + ab****b dp[i][j]=dp[i+1][i] + a****ab dp[i][j]=dp[i][j-1] +*/ +func LongestPalindromeSubseq(s string) int { + n := len(s) + // ๅˆๅง‹ๅŒ– dp table : [][]int{} + dp := make([][]int, n) + for i := 0; i < n; i++ { + dp[i] = make([]int, n) + // Base case + dp[i][i] = 1 + } + + // ๅๅ‘้ๆญท็ขบไฟๆญฃ็ขบ็š„็‹€ๆ…‹่ฝ‰็งป + for i := n - 2; i >= 0; i-- { + for j := i + 1; j < n; j++ { + if s[i] == s[j] { + dp[i][j] = dp[i+1][j-1] + 2 + } else { + dp[i][j] = max(dp[i+1][j], dp[i][j-1]) + } + // fmt.Printf("[%d][%d] = %d \n", i, j, dp[i][j]) + } + } + return dp[0][n-1] +} + +type numbers interface { + int | int8 | int16 | int32 | int64 | float32 | float64 +} + +func max[T numbers](a T, b T) T { + if a > b { + return a + } + return b +} diff --git a/Leetcode/0516.Longest-Palindromic-Subsequence/main_test.go b/Leetcode/0516.Longest-Palindromic-Subsequence/main_test.go new file mode 100644 index 000000000..4e3bca5fa --- /dev/null +++ b/Leetcode/0516.Longest-Palindromic-Subsequence/main_test.go @@ -0,0 +1,37 @@ +package longestpalindromicsubsequence + +import "testing" + +var tests = []struct { + arg1 string + want int +}{ + { + "bbbab", + 4, + }, + { + "cbbd", + 2, + }, +} + +func TestLongestPalindromeSubseq(t *testing.T) { + for _, tt := range tests { + if got := LongestPalindromeSubseq(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestPalindromeSubseq(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestPalindromeSubseq(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0543.Diameter-of-Binary-Tree/index.html b/Leetcode/0543.Diameter-of-Binary-Tree/index.html new file mode 100644 index 000000000..ccc675139 --- /dev/null +++ b/Leetcode/0543.Diameter-of-Binary-Tree/index.html @@ -0,0 +1,3865 @@ + + + + + + + 0543. Diameter of Binary Tree ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                  543. Diameter of Binary Tree

                                                                                                                                                                                                                  題目

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  Given the root of a binary tree, return the length of the diameter of the tree.

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  The length of a path between two nodes is represented by the number of edges between them.

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  Example 1:

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  Input: root = [1,2,3,4,5] +Output: 3 +Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. +Example 2:

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  Input: root = [1,2] +Output: 1

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  Constraints:

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  The number of nodes in the tree is in the range [1, 104]. +-100 <= Node.val <= 100

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  題目大意

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  解題思路

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  左邊的最高高度與右邊的最高高度相加

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  Big O

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  時間複雜 O(n), +空間複雜: 最壞 O(n), 平衡樹 O(log(n))

                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  來源

                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  package diameterofbinarytree
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +import "LeetcodeGolang/structures"
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +/**
                                                                                                                                                                                                                  + * Definition for a binary tree node.
                                                                                                                                                                                                                  + * type TreeNode struct {
                                                                                                                                                                                                                  + *     Val int
                                                                                                                                                                                                                  + *     Left *TreeNode
                                                                                                                                                                                                                  + *     Right *TreeNode
                                                                                                                                                                                                                  + * }
                                                                                                                                                                                                                  + */
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +type TreeNode = structures.TreeNode
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +var maxDiameter int
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +// 時間複雜 O(n), 空間複雜: 最壞 O(n), 平衡樹 O(log(n))
                                                                                                                                                                                                                  +func DiameterOfBinaryTree(root *TreeNode) int {
                                                                                                                                                                                                                  +    if root == nil {
                                                                                                                                                                                                                  +        return 0
                                                                                                                                                                                                                  +    }
                                                                                                                                                                                                                  +    maxDiameter = 0
                                                                                                                                                                                                                  +    maxDepth(root)
                                                                                                                                                                                                                  +    return maxDiameter
                                                                                                                                                                                                                  +}
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +func maxDepth(node *TreeNode) int {
                                                                                                                                                                                                                  +    if node == nil {
                                                                                                                                                                                                                  +        return 0
                                                                                                                                                                                                                  +    }
                                                                                                                                                                                                                  +    left := maxDepth(node.Left)
                                                                                                                                                                                                                  +    right := maxDepth(node.Right)
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +    maxDiameter = max(maxDiameter, left+right)
                                                                                                                                                                                                                  +    return max(left, right) + 1
                                                                                                                                                                                                                  +}
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +func max(a, b int) int {
                                                                                                                                                                                                                  +    if a >= b {
                                                                                                                                                                                                                  +        return a
                                                                                                                                                                                                                  +    } else {
                                                                                                                                                                                                                  +        return b
                                                                                                                                                                                                                  +    }
                                                                                                                                                                                                                  +}
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +

                                                                                                                                                                                                                  Benchmark

                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  +
                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                  results matching ""

                                                                                                                                                                                                                  +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                    No results matching ""

                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    + + + + + + +
                                                                                                                                                                                                                    + + +
                                                                                                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0543.Diameter-of-Binary-Tree/main.go b/Leetcode/0543.Diameter-of-Binary-Tree/main.go new file mode 100644 index 000000000..e733a119b --- /dev/null +++ b/Leetcode/0543.Diameter-of-Binary-Tree/main.go @@ -0,0 +1,45 @@ +package diameterofbinarytree + +import "LeetcodeGolang/structures" + +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ + +type TreeNode = structures.TreeNode + +var maxDiameter int + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ: ๆœ€ๅฃž O(n), ๅนณ่กกๆจน O(log(n)) +func DiameterOfBinaryTree(root *TreeNode) int { + if root == nil { + return 0 + } + maxDiameter = 0 + maxDepth(root) + return maxDiameter +} + +func maxDepth(node *TreeNode) int { + if node == nil { + return 0 + } + left := maxDepth(node.Left) + right := maxDepth(node.Right) + + maxDiameter = max(maxDiameter, left+right) + return max(left, right) + 1 +} + +func max(a, b int) int { + if a >= b { + return a + } else { + return b + } +} diff --git a/Leetcode/0543.Diameter-of-Binary-Tree/main_test.go b/Leetcode/0543.Diameter-of-Binary-Tree/main_test.go new file mode 100644 index 000000000..006d5659d --- /dev/null +++ b/Leetcode/0543.Diameter-of-Binary-Tree/main_test.go @@ -0,0 +1,43 @@ +package diameterofbinarytree + +import ( + "LeetcodeGolang/structures" + "testing" +) + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{1, 2, 3, 4, 5}, + 3, + }, + { + []int{1, 2}, + 1, + }, +} + +func TestDiameterOfBinaryTree(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + root := structures.Ints2TreeNode(tt.arg1) + if got := DiameterOfBinaryTree(root); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkDiameterOfBinaryTree(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + root := structures.Ints2TreeNode(tests[0].arg1) + DiameterOfBinaryTree(root) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0567.Permutation-in-String/index.html b/Leetcode/0567.Permutation-in-String/index.html new file mode 100644 index 000000000..3915ccd69 --- /dev/null +++ b/Leetcode/0567.Permutation-in-String/index.html @@ -0,0 +1,3899 @@ + + + + + + + 0567.Permutation in String ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                    567. Permutation in String

                                                                                                                                                                                                                    題目

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    In other words, return true if one of s1's permutations is the substring of s2.

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    Example 1:

                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    Input: s1 = "ab", s2 = "eidbaooo"
                                                                                                                                                                                                                    +Output: true
                                                                                                                                                                                                                    +Explanation: s2 contains one permutation of s1 ("ba").
                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    Example 2:

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    Input: s1 = "ab", s2 = "eidboaoo" +Output: false

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    Constraints:

                                                                                                                                                                                                                    +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                    • 1 <= s1.length, s2.length <= 104
                                                                                                                                                                                                                    • +
                                                                                                                                                                                                                    • s1 and s2 consist of lowercase English letters.
                                                                                                                                                                                                                    • +
                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    題目大意

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    輸入兩個String S1 和 S2 , 判斷 S2 是否包含S1的排列, 也就是要判斷 S2 中是否存在一個子字串是S1的一種全排列

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    解題思路

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    Sliding Window +可以用 slice 取代 map 來優化

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    來源

                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                    解答

                                                                                                                                                                                                                    +

                                                                                                                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0567.Permutation-in-String/main.go

                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    package permutationinstring
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +func CheckInclusion(s1 string, s2 string) bool {
                                                                                                                                                                                                                    +    need, window := make(map[rune]int), make(map[rune]int)
                                                                                                                                                                                                                    +    for _, c := range s1 {
                                                                                                                                                                                                                    +        need[c]++
                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +    left, right := 0, 0
                                                                                                                                                                                                                    +    valid := 0
                                                                                                                                                                                                                    +    for right < len(s2) {
                                                                                                                                                                                                                    +        c := rune(s2[right])
                                                                                                                                                                                                                    +        right++
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +        // 進行窗口內數據的一系列更新
                                                                                                                                                                                                                    +        if need[c] > 0 {
                                                                                                                                                                                                                    +            window[c]++
                                                                                                                                                                                                                    +            if window[c] == need[c] {
                                                                                                                                                                                                                    +                // 該字符長度達到
                                                                                                                                                                                                                    +                valid++
                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +        // fmt.Printf("[%d,%d) \n", left, right)
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +        // 判斷左視窗是否要收縮
                                                                                                                                                                                                                    +        // for (right - left) >= len(s1)
                                                                                                                                                                                                                    +        if (right - left) >= len(s1) {
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +            if valid == len(need) {
                                                                                                                                                                                                                    +                // 全找到
                                                                                                                                                                                                                    +                return true
                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                    +            d := rune(s2[left])
                                                                                                                                                                                                                    +            left++
                                                                                                                                                                                                                    +            if need[d] > 0 {
                                                                                                                                                                                                                    +                if window[d] == need[d] {
                                                                                                                                                                                                                    +                    valid--
                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                    +                window[d]--
                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                    +    return false
                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +// 用 slice 取代 map 來優化
                                                                                                                                                                                                                    +func CheckInclusionSlice(s1 string, s2 string) bool {
                                                                                                                                                                                                                    +    need := [256]int{}
                                                                                                                                                                                                                    +    for _, c := range s1 {
                                                                                                                                                                                                                    +        need[c-'a']++
                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +    left, right := 0, 0
                                                                                                                                                                                                                    +    count := len(s1)
                                                                                                                                                                                                                    +    for right < len(s2) {
                                                                                                                                                                                                                    +        c := s2[right] - 'a'
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +        if need[c] > 0 {
                                                                                                                                                                                                                    +            // 有找到
                                                                                                                                                                                                                    +            count--
                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                    +        need[c]--
                                                                                                                                                                                                                    +        right++
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +        // fmt.Printf("[%d,%d)\n", left, right)
                                                                                                                                                                                                                    +        if count == 0 {
                                                                                                                                                                                                                    +            return true
                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +        // 判斷左視窗是否要收縮
                                                                                                                                                                                                                    +        if (right - left) == len(s1) {
                                                                                                                                                                                                                    +            d := s2[left] - 'a'
                                                                                                                                                                                                                    +            if need[d] >= 0 {
                                                                                                                                                                                                                    +                // 符合預期的長度, 但是卻沒找到預期的結果
                                                                                                                                                                                                                    +                count++
                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                    +            need[d]++
                                                                                                                                                                                                                    +            left++
                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                    +    return false
                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    tags: Medium Leetcode Sliding Window
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    +
                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                    results matching ""

                                                                                                                                                                                                                    +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                      No results matching ""

                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      + + + + + + +
                                                                                                                                                                                                                      + + +
                                                                                                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0567.Permutation-in-String/main.go b/Leetcode/0567.Permutation-in-String/main.go new file mode 100644 index 000000000..be5e2bb18 --- /dev/null +++ b/Leetcode/0567.Permutation-in-String/main.go @@ -0,0 +1,83 @@ +package permutationinstring + +func CheckInclusion(s1 string, s2 string) bool { + need, window := make(map[rune]int), make(map[rune]int) + for _, c := range s1 { + need[c]++ + } + + left, right := 0, 0 + valid := 0 + for right < len(s2) { + c := rune(s2[right]) + right++ + + // ้€ฒ่กŒ็ช—ๅฃๅ…งๆ•ธๆ“š็š„ไธ€็ณปๅˆ—ๆ›ดๆ–ฐ + if need[c] > 0 { + window[c]++ + if window[c] == need[c] { + // ่ฉฒๅญ—็ฌฆ้•ทๅบฆ้”ๅˆฐ + valid++ + } + } + + // fmt.Printf("[%d,%d) \n", left, right) + + // ๅˆคๆ–ทๅทฆ่ฆ–็ช—ๆ˜ฏๅฆ่ฆๆ”ถ็ธฎ + // for (right - left) >= len(s1) + if (right - left) >= len(s1) { + + if valid == len(need) { + // ๅ…จๆ‰พๅˆฐ + return true + } + d := rune(s2[left]) + left++ + if need[d] > 0 { + if window[d] == need[d] { + valid-- + } + window[d]-- + } + } + } + return false +} + +// ็”จ slice ๅ–ไปฃ map ไพ†ๅ„ชๅŒ– +func CheckInclusionSlice(s1 string, s2 string) bool { + need := [256]int{} + for _, c := range s1 { + need[c-'a']++ + } + + left, right := 0, 0 + count := len(s1) + for right < len(s2) { + c := s2[right] - 'a' + + if need[c] > 0 { + // ๆœ‰ๆ‰พๅˆฐ + count-- + } + need[c]-- + right++ + + // fmt.Printf("[%d,%d)\n", left, right) + if count == 0 { + return true + } + + // ๅˆคๆ–ทๅทฆ่ฆ–็ช—ๆ˜ฏๅฆ่ฆๆ”ถ็ธฎ + if (right - left) == len(s1) { + d := s2[left] - 'a' + if need[d] >= 0 { + // ็ฌฆๅˆ้ ๆœŸ็š„้•ทๅบฆ, ไฝ†ๆ˜ฏๅปๆฒ’ๆ‰พๅˆฐ้ ๆœŸ็š„็ตๆžœ + count++ + } + need[d]++ + left++ + } + } + return false +} diff --git a/Leetcode/0567.Permutation-in-String/main_test.go b/Leetcode/0567.Permutation-in-String/main_test.go new file mode 100644 index 000000000..58f56f202 --- /dev/null +++ b/Leetcode/0567.Permutation-in-String/main_test.go @@ -0,0 +1,62 @@ +package permutationinstring + +import "testing" + +var tests = []struct { + arg1 string + arg2 string + want bool +}{ + { + "ab", + "eidbaooo", + true, + }, + { + "ab", + "eidboaoo", + false, + }, +} + +func TestCheckInclusion(t *testing.T) { + for _, tt := range tests { + if got := CheckInclusion(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestCheckInclusionSlice(t *testing.T) { + for _, tt := range tests { + if got := CheckInclusionSlice(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkCheckInclusion(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + CheckInclusion(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkCheckInclusionSlice(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + CheckInclusionSlice(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0567.Permutation-in-String -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0567.Permutation-in-String +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkCheckInclusion-8 9091321 167.9 ns/op 0 B/op 0 allocs/op +BenchmarkCheckInclusionSlice-8 26744336 53.28 ns/op 0 B/op 0 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0567.Permutation-in-String 3.143s +*/ diff --git a/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits.go b/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits.go new file mode 100644 index 000000000..a6de38e25 --- /dev/null +++ b/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits.go @@ -0,0 +1,38 @@ +package binarynumberwithalternatingbits + +// ๆšดๅŠ›่งฃ O(n) +func hasAlternatingBits(n int) bool { + for n > 0 { + preBit := n & 1 + n = n / 2 + curBit := n & 1 + if curBit == preBit { + return false + } + } + return true +} + +// ๆ•ธๅญธ่งฃ +func hasAlternatingBits2(n int) bool { + /* + n=5 + n= 1 0 1 + n >> 1 0 1 0 + n^(n>>1) 1 1 1 (XOR ไธๅŒๆ™‚ๅพ—1) + n 1 1 1 + n+1 1 0 0 0 + n & (n+1) 0 0 0 + + n=7 + n= 1 1 1 + n >> 1 0 1 1 + n^(n>>1) 1 0 0 (XOR ไธๅŒๆ™‚ๅพ—1) + n 1 0 0 + n+1 1 0 1 + n & (n+1) 1 0 0 + */ + n = n ^ (n >> 1) + result := n & (n + 1) + return result == 0 +} diff --git a/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits_test.go b/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits_test.go new file mode 100644 index 000000000..42fe644e9 --- /dev/null +++ b/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits_test.go @@ -0,0 +1,61 @@ +package binarynumberwithalternatingbits + +import "testing" + +var tests = []struct { + arg1 int + want bool +}{ + { + 5, + true, + }, + { + 7, + false, + }, + { + 11, + false, + }, + { + 10, + true, + }, +} + +func TestHasAlternatingBits(t *testing.T) { + for _, tt := range tests { + if got := hasAlternatingBits(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestHasAlternatingBits2(t *testing.T) { + for _, tt := range tests { + if got := hasAlternatingBits2(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkHasAlternatingBits(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + hasAlternatingBits(10) + } +} + +func BenchmarkHasAlternatingBits2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + hasAlternatingBits2(10) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0693.Binary-Number-with-Alternating-Bits -bench=. +BenchmarkHasAlternatingBits-8 300204136 3.979 ns/op 0 B/op 0 allocs/op +BenchmarkHasAlternatingBits2-8 1000000000 0.3335 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Leetcode/0693.Binary-Number-with-Alternating-Bits/index.html b/Leetcode/0693.Binary-Number-with-Alternating-Bits/index.html new file mode 100644 index 000000000..2f9912fcd --- /dev/null +++ b/Leetcode/0693.Binary-Number-with-Alternating-Bits/index.html @@ -0,0 +1,3864 @@ + + + + + + + 0693.Binary Number with Alternating Bits ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                      693. Binary Number with Alternating Bits

                                                                                                                                                                                                                      題目

                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      Example 1:

                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      Input: 5
                                                                                                                                                                                                                      +Output: True
                                                                                                                                                                                                                      +Explanation:
                                                                                                                                                                                                                      +The binary representation of 5 is: 101
                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      Example 2:

                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      Input: 7
                                                                                                                                                                                                                      +Output: False
                                                                                                                                                                                                                      +Explanation:
                                                                                                                                                                                                                      +The binary representation of 7 is: 111.
                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      Example 3:

                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      Input: 11
                                                                                                                                                                                                                      +Output: False
                                                                                                                                                                                                                      +Explanation:
                                                                                                                                                                                                                      +The binary representation of 11 is: 1011.
                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      Example 4:

                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      Input: 10
                                                                                                                                                                                                                      +Output: True
                                                                                                                                                                                                                      +Explanation:
                                                                                                                                                                                                                      +The binary representation of 10 is: 1010.
                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      題目大意

                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      給定一個正整數,檢查他是否為交替位二進制數:換句話說,就是他的二進制數相鄰的兩個位數永不相等。

                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      解題思路

                                                                                                                                                                                                                      +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                      • 判斷一個數的二進制位相鄰兩個數是不相等的,即 0101 交叉間隔的,如果是,輸出 true。這一題有多種做法,最簡單的方法就是直接模擬。比較巧妙的方法是通過位運算,合理構造特殊數據進行位運算到達目的。 010101 構造出 101010 兩者相互 & 位運算以後就為 0,因為都“插空”了。
                                                                                                                                                                                                                      • +
                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      提示:

                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      1 <= n <= 2^31 - 1

                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      來源

                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                      解答

                                                                                                                                                                                                                      +

                                                                                                                                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits.go

                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      package binarynumberwithalternatingbits
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      +// 暴力解 O(n)
                                                                                                                                                                                                                      +func hasAlternatingBits(n int) bool {
                                                                                                                                                                                                                      +    for n > 0 {
                                                                                                                                                                                                                      +        preBit := n & 1
                                                                                                                                                                                                                      +        n = n / 2
                                                                                                                                                                                                                      +        curBit := n & 1
                                                                                                                                                                                                                      +        if curBit == preBit {
                                                                                                                                                                                                                      +            return false
                                                                                                                                                                                                                      +        }
                                                                                                                                                                                                                      +    }
                                                                                                                                                                                                                      +    return true
                                                                                                                                                                                                                      +}
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      +// 數學解
                                                                                                                                                                                                                      +func hasAlternatingBits2(n int) bool {
                                                                                                                                                                                                                      +    /*
                                                                                                                                                                                                                      +        n=5
                                                                                                                                                                                                                      +        n=                1 0 1
                                                                                                                                                                                                                      +        n >> 1            0 1 0
                                                                                                                                                                                                                      +        n^(n>>1)        1 1 1  (XOR 不同時得1)
                                                                                                                                                                                                                      +        n               1 1 1
                                                                                                                                                                                                                      +        n+1              1 0 0 0
                                                                                                                                                                                                                      +        n & (n+1)        0 0 0
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      +        n=7
                                                                                                                                                                                                                      +        n=                1 1 1
                                                                                                                                                                                                                      +        n >> 1            0 1 1
                                                                                                                                                                                                                      +        n^(n>>1)        1 0 0  (XOR 不同時得1)
                                                                                                                                                                                                                      +        n               1 0 0
                                                                                                                                                                                                                      +        n+1                1 0 1
                                                                                                                                                                                                                      +        n & (n+1)        1 0 0
                                                                                                                                                                                                                      +    */
                                                                                                                                                                                                                      +    n = n ^ (n >> 1)
                                                                                                                                                                                                                      +    result := n & (n + 1)
                                                                                                                                                                                                                      +    return result == 0
                                                                                                                                                                                                                      +}
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      +
                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                      results matching ""

                                                                                                                                                                                                                      +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                        No results matching ""

                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        + + + + + + +
                                                                                                                                                                                                                        + + +
                                                                                                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0695.Max-Area-of-Island/images/maxarea1-grid.jpg b/Leetcode/0695.Max-Area-of-Island/images/maxarea1-grid.jpg new file mode 100644 index 000000000..127b54089 Binary files /dev/null and b/Leetcode/0695.Max-Area-of-Island/images/maxarea1-grid.jpg differ diff --git a/Leetcode/0695.Max-Area-of-Island/index.html b/Leetcode/0695.Max-Area-of-Island/index.html new file mode 100644 index 000000000..fd79de33d --- /dev/null +++ b/Leetcode/0695.Max-Area-of-Island/index.html @@ -0,0 +1,3886 @@ + + + + + + + 0695.Max Area of Island ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                        695. Max Area of Island

                                                                                                                                                                                                                        題目

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        The area of an island is the number of cells with a value 1 in the island.

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        Return the maximum area of an island in grid. If there is no island, return 0.

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        Example 1:

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
                                                                                                                                                                                                                        +Output: 6
                                                                                                                                                                                                                        +Explanation: The answer is not 11, because the island must be connected 4-directionally.
                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        Example 2:

                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        Input: grid = [[0,0,0,0,0,0,0,0]]
                                                                                                                                                                                                                        +Output: 0
                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        Constraints:

                                                                                                                                                                                                                        +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                        • m == grid.length
                                                                                                                                                                                                                        • +
                                                                                                                                                                                                                        • n == grid[i].length
                                                                                                                                                                                                                        • +
                                                                                                                                                                                                                        • 1 <= m, n <= 50
                                                                                                                                                                                                                        • +
                                                                                                                                                                                                                        • grid[i][j] is either 0 or 1.
                                                                                                                                                                                                                        • +
                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        題目大意

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        給定一個由 '1'(陸地)和 '0'(水域)組成的二維矩陣,計算矩陣中連續的1所組成的最大區域的面積。

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        解題思路

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        使用BFS或DFS遍歷矩陣,計算每個島嶼的面積,並找到最大的面積值。 +給出一個地圖,要求計算上面島嶼的。注意島嶼的定義是要求都是海(為0的點),如果土地(為1的點)靠在地圖邊緣,不能是珊瑚島。 +這題和第200題,第1254題解題思路是一致的。 +DPS深搜。不過這題需要多處理2件事情,一是注意靠邊緣的島嶼不能計算關係,二是動態維護島嶼的最大面積。

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        使用DFS的解法:

                                                                                                                                                                                                                        +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                        1. 創建一個變量maxArea,用於記錄最大面積,初始化為0。
                                                                                                                                                                                                                        2. +
                                                                                                                                                                                                                        3. 遍歷二維網格,對於每個為1的位置,調用dfs函數計算以該位置為起點的島嶼面積。
                                                                                                                                                                                                                        4. +
                                                                                                                                                                                                                        5. 在dfs函數中,首先檢查當前位置的合法性,如果超出網格範圍或者該位置已經訪問過或者是水域(0),則返回0。
                                                                                                                                                                                                                        6. +
                                                                                                                                                                                                                        7. 將當前位置標記為已訪問,並初始化面積為1。
                                                                                                                                                                                                                        8. +
                                                                                                                                                                                                                        9. 遞迴地對當前位置的上、下、左、右四個相鄰位置進行dfs,並將返回的面積加到當前面積上。
                                                                                                                                                                                                                        10. +
                                                                                                                                                                                                                        11. 返回當前面積。
                                                                                                                                                                                                                        12. +
                                                                                                                                                                                                                        13. 更新maxArea為當前面積和maxArea中的較大值。
                                                                                                                                                                                                                        14. +
                                                                                                                                                                                                                        15. 遍歷完整個網格後,返回maxArea作為結果。
                                                                                                                                                                                                                        16. +
                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        時間複雜度: 遍歷整個網格的時間複雜度為O(mn),其中m和n分別為網格的行數和列數。 +空間複雜度: 使用了遞迴調用的栈空間,空間複雜度為O(mn)。

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        來源

                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                        解答

                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0695.Max-Area-of-Island/main.go

                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        package maxareaofisland
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +var (
                                                                                                                                                                                                                        +    dir = [][]int{
                                                                                                                                                                                                                        +        {-1, 0}, // 上
                                                                                                                                                                                                                        +        {0, 1},  // 右
                                                                                                                                                                                                                        +        {1, 0},  // 下
                                                                                                                                                                                                                        +        {0, -1}, // 左
                                                                                                                                                                                                                        +    }
                                                                                                                                                                                                                        +)
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +func MaxAreaOfIsland(grid [][]int) int {
                                                                                                                                                                                                                        +    result := 0
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +    for i, row := range grid {
                                                                                                                                                                                                                        +        for j, col := range row {
                                                                                                                                                                                                                        +            if col == 1 {
                                                                                                                                                                                                                        +                result = max(result, areaOfIsland(grid, i, j))
                                                                                                                                                                                                                        +            }
                                                                                                                                                                                                                        +        }
                                                                                                                                                                                                                        +    }
                                                                                                                                                                                                                        +    return result
                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +// DFS
                                                                                                                                                                                                                        +func areaOfIsland(grid [][]int, x, y int) int {
                                                                                                                                                                                                                        +    if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) || grid[x][y] == 0 {
                                                                                                                                                                                                                        +        return 0
                                                                                                                                                                                                                        +    }
                                                                                                                                                                                                                        +    // 設為0,避免重複計算
                                                                                                                                                                                                                        +    grid[x][y] = 0
                                                                                                                                                                                                                        +    total := 1
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +    // 四個方向查找
                                                                                                                                                                                                                        +    for i := 0; i < 4; i++ {
                                                                                                                                                                                                                        +        nx := x + dir[i][0]
                                                                                                                                                                                                                        +        ny := y + dir[i][1]
                                                                                                                                                                                                                        +        total += areaOfIsland(grid, nx, ny)
                                                                                                                                                                                                                        +    }
                                                                                                                                                                                                                        +    return total
                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +func max(x, y int) int {
                                                                                                                                                                                                                        +    if x > y {
                                                                                                                                                                                                                        +        return x
                                                                                                                                                                                                                        +    }
                                                                                                                                                                                                                        +    return y
                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +

                                                                                                                                                                                                                        Benchmark

                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        +
                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                        results matching ""

                                                                                                                                                                                                                        +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                          No results matching ""

                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          + + + + + + +
                                                                                                                                                                                                                          + + +
                                                                                                                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0695.Max-Area-of-Island/main.go b/Leetcode/0695.Max-Area-of-Island/main.go new file mode 100644 index 000000000..284a9a90d --- /dev/null +++ b/Leetcode/0695.Max-Area-of-Island/main.go @@ -0,0 +1,48 @@ +package maxareaofisland + +var ( + dir = [][]int{ + {-1, 0}, // ไธŠ + {0, 1}, // ๅณ + {1, 0}, // ไธ‹ + {0, -1}, // ๅทฆ + } +) + +func MaxAreaOfIsland(grid [][]int) int { + result := 0 + + for i, row := range grid { + for j, col := range row { + if col == 1 { + result = max(result, areaOfIsland(grid, i, j)) + } + } + } + return result +} + +// DFS +func areaOfIsland(grid [][]int, x, y int) int { + if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) || grid[x][y] == 0 { + return 0 + } + // ่จญ็‚บ0๏ผŒ้ฟๅ…้‡่ค‡่จˆ็ฎ— + grid[x][y] = 0 + total := 1 + + // ๅ››ๅ€‹ๆ–นๅ‘ๆŸฅๆ‰พ + for i := 0; i < 4; i++ { + nx := x + dir[i][0] + ny := y + dir[i][1] + total += areaOfIsland(grid, nx, ny) + } + return total +} + +func max(x, y int) int { + if x > y { + return x + } + return y +} diff --git a/Leetcode/0695.Max-Area-of-Island/main_test.go b/Leetcode/0695.Max-Area-of-Island/main_test.go new file mode 100644 index 000000000..c32b10b65 --- /dev/null +++ b/Leetcode/0695.Max-Area-of-Island/main_test.go @@ -0,0 +1,38 @@ +package maxareaofisland + +import "testing" + +var tests = []struct { + arg1 [][]int + want int +}{ + { + [][]int{{0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0}, {0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0}}, + 6, + }, + { + [][]int{{0, 0, 0, 0, 0, 0, 0, 0}}, + 0, + }, +} + +func TestMaxAreaOfIsland(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MaxAreaOfIsland(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkMaxAreaOfIsland(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MaxAreaOfIsland(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0695.Max-Area-of-Island -bench=. + +*/ diff --git a/Leetcode/0703.Kth-Largest-Element-in-a-Stream/index.html b/Leetcode/0703.Kth-Largest-Element-in-a-Stream/index.html new file mode 100644 index 000000000..6d56d1e62 --- /dev/null +++ b/Leetcode/0703.Kth-Largest-Element-in-a-Stream/index.html @@ -0,0 +1,3901 @@ + + + + + + + 0703. Kth Largest Element in a Stream ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                          0703. Kth Largest Element in a Stream

                                                                                                                                                                                                                          題目

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Implement KthLargest class:

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. +int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream.

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Example 1:

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Input +["KthLargest", "add", "add", "add", "add", "add"] +[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] +Output +[null, 4, 5, 5, 8, 8]

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Explanation +KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); +kthLargest.add(3); // return 4 +kthLargest.add(5); // return 5 +kthLargest.add(10); // return 5 +kthLargest.add(9); // return 8 +kthLargest.add(4); // return 8

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Constraints:

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          1 <= k <= 104 +0 <= nums.length <= 104 +-104 <= nums[i] <= 104 +-104 <= val <= 104 +At most 104 calls will be made to add. +It is guaranteed that there will be at least k elements in the array when you search for the kth element. +Accepted +479.1K +Submissions +846.4K +Acceptance Rate +56.6%

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          題目大意

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          設計一個找到數據流中第 k 大元素的類(class)。 注意是排序後的第 k 大元素,不是第 k 個不同的元素。 請實現 KthLargest 類:

                                                                                                                                                                                                                          +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                          • KthLargest(int k, int[] nums) 使用整數 k 和整數流 nums 初始化物件。
                                                                                                                                                                                                                          • +
                                                                                                                                                                                                                          • int add(int val) 將 val 插入數據流 nums 後,返回當前數據流中第 k 大的元素。
                                                                                                                                                                                                                          • +
                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          解題思路

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          這題考察優先順序佇列的使用,可以先做下這道類似的題目 215.陣列中的第 K 個最大元素

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          golang container/heap

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Big O

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          時間複雜 : +初始化時間複雜度為: O(nlog⁡k) ,其中 n 為初始化時 nums 的長度; +單次插入時間複雜度為: O(log⁡k)

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          空間複雜 : O(k)。 需要使用優先佇列存儲前 k 大的元素

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          來源

                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                          解答

                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main.go

                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          package kthlargestelementinastream
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +import (
                                                                                                                                                                                                                          +    "container/heap"
                                                                                                                                                                                                                          +    "sort"
                                                                                                                                                                                                                          +)
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +/**
                                                                                                                                                                                                                          + * Your KthLargest object will be instantiated and called as such:
                                                                                                                                                                                                                          + * obj := Constructor(k, nums);
                                                                                                                                                                                                                          + * param_1 := obj.Add(val);
                                                                                                                                                                                                                          + */
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                                                                                          +type KthLargest struct {
                                                                                                                                                                                                                          +    sort.IntSlice
                                                                                                                                                                                                                          +    k int
                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +func Constructor(k int, nums []int) KthLargest {
                                                                                                                                                                                                                          +    kl := KthLargest{k: k}
                                                                                                                                                                                                                          +    for _, val := range nums {
                                                                                                                                                                                                                          +        kl.Add(val)
                                                                                                                                                                                                                          +    }
                                                                                                                                                                                                                          +    return kl
                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +func (kl *KthLargest) Add(val int) int {
                                                                                                                                                                                                                          +    heap.Push(kl, val)
                                                                                                                                                                                                                          +    if kl.Len() > kl.k {
                                                                                                                                                                                                                          +        heap.Pop(kl)
                                                                                                                                                                                                                          +    }
                                                                                                                                                                                                                          +    return kl.IntSlice[0]
                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +func (kl *KthLargest) Push(v interface{}) {
                                                                                                                                                                                                                          +    kl.IntSlice = append(kl.IntSlice, v.(int))
                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +func (kl *KthLargest) Pop() interface{} {
                                                                                                                                                                                                                          +    a := kl.IntSlice
                                                                                                                                                                                                                          +    v := a[len(a)-1]
                                                                                                                                                                                                                          +    kl.IntSlice = a[:len(a)-1]
                                                                                                                                                                                                                          +    return v
                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +func KthLargestStream(k int, nums []int, elem []int) []int {
                                                                                                                                                                                                                          +    obj := Constructor(k, nums)
                                                                                                                                                                                                                          +    result := []int{0}
                                                                                                                                                                                                                          +    for _, val := range elem {
                                                                                                                                                                                                                          +        obj.Add(val)
                                                                                                                                                                                                                          +        result = append(result, obj.IntSlice[0])
                                                                                                                                                                                                                          +    }
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +    return result
                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +

                                                                                                                                                                                                                          Benchmark

                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          +
                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                          results matching ""

                                                                                                                                                                                                                          +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                            No results matching ""

                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            + + + + + + +
                                                                                                                                                                                                                            + + +
                                                                                                                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main.go b/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main.go new file mode 100644 index 000000000..d3e8e2f09 --- /dev/null +++ b/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main.go @@ -0,0 +1,61 @@ +package kthlargestelementinastream + +import ( + "container/heap" + "sort" +) + +// ๆ™‚้–“่ค‡้›œ : +// ๅˆๅง‹ๅŒ–ๆ™‚้–“่ค‡้›œๅบฆ็‚บ๏ผš O(nlogโกk) ๏ผŒๅ…ถไธญ n ็‚บๅˆๅง‹ๅŒ–ๆ™‚ nums ็š„้•ทๅบฆ; +// ๅ–ฎๆฌกๆ’ๅ…ฅๆ™‚้–“่ค‡้›œๅบฆ็‚บ๏ผš O(logโกk) + +// ็ฉบ้–“่ค‡้›œ : O(k)ใ€‚ ้œ€่ฆไฝฟ็”จๅ„ชๅ…ˆไฝ‡ๅˆ—ๅญ˜ๅ„ฒๅ‰ k ๅคง็š„ๅ…ƒ็ด  +type KthLargest struct { + sort.IntSlice + k int +} + +func Constructor(k int, nums []int) KthLargest { + kl := KthLargest{k: k} + for _, val := range nums { + kl.Add(val) + } + return kl +} + +func (kl *KthLargest) Add(val int) int { + heap.Push(kl, val) + if kl.Len() > kl.k { + heap.Pop(kl) + } + return kl.IntSlice[0] +} + +func (kl *KthLargest) Push(v interface{}) { + kl.IntSlice = append(kl.IntSlice, v.(int)) +} + +func (kl *KthLargest) Pop() interface{} { + // ๆ‹ฟๅ‡บๆœ€ๅพŒไธ€็ญ† + a := kl.IntSlice + v := a[len(a)-1] + kl.IntSlice = a[:len(a)-1] + return v +} + +/** + * Your KthLargest object will be instantiated and called as such: + * obj := Constructor(k, nums); + * param_1 := obj.Add(val); + */ + +func KthLargestStream(k int, nums []int, elem []int) []int { + obj := Constructor(k, nums) + result := []int{0} + for _, val := range elem { + obj.Add(val) + result = append(result, obj.IntSlice[0]) + } + + return result +} diff --git a/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main_test.go b/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main_test.go new file mode 100644 index 000000000..8fedc9628 --- /dev/null +++ b/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main_test.go @@ -0,0 +1,41 @@ +package kthlargestelementinastream + +import ( + "reflect" + "testing" +) + +var tests = []struct { + arg1 int + arg2 []int + arg3 []int + want []int +}{ + { + 3, + []int{4, 5, 8, 2}, + []int{3, 5, 10, 9, 4}, + []int{0, 4, 5, 5, 8, 8}, + }, +} + +func TestKthLargestStream(t *testing.T) { + for _, tt := range tests { + if got := KthLargestStream(tt.arg1, tt.arg2, tt.arg3); !reflect.DeepEqual(got, tt.want) { + // if got := KthLargestStream(tt.arg1, tt.arg2, tt.arg3); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkKthLargestStream(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + KthLargestStream(tests[0].arg1, tests[0].arg2, tests[0].arg3) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git a/Leetcode/0704.Binary-Search/index.html b/Leetcode/0704.Binary-Search/index.html new file mode 100644 index 000000000..c02f9d5b3 --- /dev/null +++ b/Leetcode/0704.Binary-Search/index.html @@ -0,0 +1,3932 @@ + + + + + + + 0704.Binary Search ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                            704. Binary Search

                                                                                                                                                                                                                            題目

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1.

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            You must write an algorithm with O(log n) runtime complexity.

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            Example 1:

                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            Input: nums = [-1,0,3,5,9,12], target = 9
                                                                                                                                                                                                                            +Output: 4
                                                                                                                                                                                                                            +Explanation: 9 exists in nums and its index is 4
                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            Example 2:

                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            Input: nums = [-1,0,3,5,9,12], target = 2
                                                                                                                                                                                                                            +Output: -1
                                                                                                                                                                                                                            +Explanation: 2 does not exist in nums so return -1
                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            Constraints:

                                                                                                                                                                                                                            +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                            • 1 <= nums.length <= 104
                                                                                                                                                                                                                            • +
                                                                                                                                                                                                                            • -104 < nums[i], target < 104
                                                                                                                                                                                                                            • +
                                                                                                                                                                                                                            • All the integers in nums are unique.
                                                                                                                                                                                                                            • +
                                                                                                                                                                                                                            • nums is sorted in ascending order.
                                                                                                                                                                                                                            • +
                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            題目大意

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            給一個已排序過後的array, 找出target所在index +若未找到回傳 -1

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            解題思路

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            提示:

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            來源

                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                            解答

                                                                                                                                                                                                                            +

                                                                                                                                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0704.Binary-Search/main.go

                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            package binarysearch
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +import "sort"
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +func Search(nums []int, target int) int {
                                                                                                                                                                                                                            +    lenght := len(nums)
                                                                                                                                                                                                                            +    if lenght <= 0="" 1="" {="" return="" -1="" }="" left,="" right="" :="0," lenght-1="" for="" left="" <="right" mid="" +="" if="" nums[mid]="=" target="" else="" ๆ‰พๅณ้‚Š=""> target {
                                                                                                                                                                                                                            +            // 找左邊
                                                                                                                                                                                                                            +            right = mid - 1
                                                                                                                                                                                                                            +        }
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +    // 都沒找到
                                                                                                                                                                                                                            +    return -1
                                                                                                                                                                                                                            +}
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +func Search2(nums []int, target int) int {
                                                                                                                                                                                                                            +    lenght := len(nums)
                                                                                                                                                                                                                            +    if lenght <= 0="" {="" return="" -1="" }="" left,="" right="" :="0," lenght-1="" for="" left="" <="right" ้™คไปฅ2="" mid="" +="" (right-left)="">>1
                                                                                                                                                                                                                            +        mid := int(uint(right+left) >> 1)
                                                                                                                                                                                                                            +        if nums[mid] == target {
                                                                                                                                                                                                                            +            return mid
                                                                                                                                                                                                                            +        } else if nums[mid] < target {
                                                                                                                                                                                                                            +            // 找右邊
                                                                                                                                                                                                                            +            left = mid + 1
                                                                                                                                                                                                                            +        } else if nums[mid] > target {
                                                                                                                                                                                                                            +            // 找左邊
                                                                                                                                                                                                                            +            right = mid - 1
                                                                                                                                                                                                                            +        }
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +    // 都沒找到
                                                                                                                                                                                                                            +    return -1
                                                                                                                                                                                                                            +}
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +// 內建sort
                                                                                                                                                                                                                            +func BinarySearch(nums []int, target int) int {
                                                                                                                                                                                                                            +    length := len(nums)
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +    index := sort.Search(length, func(i int) bool {
                                                                                                                                                                                                                            +        return nums[i] >= target
                                                                                                                                                                                                                            +    })
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +    if index < length && nums[index] == target {
                                                                                                                                                                                                                            +        return index
                                                                                                                                                                                                                            +    } else {
                                                                                                                                                                                                                            +        return -1
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +}
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +// 使用遞迴
                                                                                                                                                                                                                            +func BinarySearchRecur(nums []int, target int) (index int) {
                                                                                                                                                                                                                            +    return BinarySearchRecursively(nums, target, 0, len(nums)-1)
                                                                                                                                                                                                                            +}
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +func BinarySearchRecursively(nums []int, target int, start int, end int) int {
                                                                                                                                                                                                                            +    if end < start {
                                                                                                                                                                                                                            +        return -1
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +    middle := int(uint(end+start) >> 1)
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +    if nums[middle] == target {
                                                                                                                                                                                                                            +        return middle
                                                                                                                                                                                                                            +    } else if target > nums[middle] {
                                                                                                                                                                                                                            +        return BinarySearchRecursively(nums, target, middle+1, end)
                                                                                                                                                                                                                            +    } else {
                                                                                                                                                                                                                            +        return BinarySearchRecursively(nums, target, start, middle-1)
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +}
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +// 有點類似 nums 小於 target的元素有幾個
                                                                                                                                                                                                                            +func LeftBound(nums []int, target int) (index int) {
                                                                                                                                                                                                                            +    lenght := len(nums)
                                                                                                                                                                                                                            +    if lenght <= 0="" {="" return="" -1="" }="" left,="" right="" :="0," lenght-1="" for="" left="" <="right" ้™คไปฅ2="" mid="" +="" (right-left)="">>1
                                                                                                                                                                                                                            +        mid := int(uint(right+left) >> 1)
                                                                                                                                                                                                                            +        if nums[mid] == target {
                                                                                                                                                                                                                            +            // 要繼續找左邊, 所以把右邊變小
                                                                                                                                                                                                                            +            right = mid - 1
                                                                                                                                                                                                                            +        } else if nums[mid] < target {
                                                                                                                                                                                                                            +            // 找右邊
                                                                                                                                                                                                                            +            left = mid + 1
                                                                                                                                                                                                                            +        } else if nums[mid] > target {
                                                                                                                                                                                                                            +            // 找左邊
                                                                                                                                                                                                                            +            right = mid - 1
                                                                                                                                                                                                                            +        }
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +    // 都沒找到 注意: left越界情況
                                                                                                                                                                                                                            +    if left >= lenght || nums[left] != target {
                                                                                                                                                                                                                            +        return -1
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +    return left
                                                                                                                                                                                                                            +}
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +func RightBound(nums []int, target int) (index int) {
                                                                                                                                                                                                                            +    lenght := len(nums)
                                                                                                                                                                                                                            +    if lenght <= 0="" {="" return="" -1="" }="" left,="" right="" :="0," lenght-1="" for="" left="" <="right" ้™คไปฅ2="" mid="" +="" (right-left)="">>1
                                                                                                                                                                                                                            +        mid := int(uint(right+left) >> 1)
                                                                                                                                                                                                                            +        if nums[mid] == target {
                                                                                                                                                                                                                            +            // 注意:要繼續找右邊, 所以把左邊變大=mid+1
                                                                                                                                                                                                                            +            left = mid + 1
                                                                                                                                                                                                                            +        } else if nums[mid] < target {
                                                                                                                                                                                                                            +            // 找右邊
                                                                                                                                                                                                                            +            left = mid + 1
                                                                                                                                                                                                                            +        } else if nums[mid] > target {
                                                                                                                                                                                                                            +            // 找左邊
                                                                                                                                                                                                                            +            right = mid - 1
                                                                                                                                                                                                                            +        }
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +    // 都沒找到 注意:right越界情況
                                                                                                                                                                                                                            +    if right < 0 || nums[right] != target {
                                                                                                                                                                                                                            +        return -1
                                                                                                                                                                                                                            +    }
                                                                                                                                                                                                                            +    return right
                                                                                                                                                                                                                            +}
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            +
                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                            results matching ""

                                                                                                                                                                                                                            +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                              No results matching ""

                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              + + + + + + +
                                                                                                                                                                                                                              + + +
                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0704.Binary-Search/main.go b/Leetcode/0704.Binary-Search/main.go new file mode 100644 index 000000000..e71808f3d --- /dev/null +++ b/Leetcode/0704.Binary-Search/main.go @@ -0,0 +1,146 @@ +package binarysearch + +import "sort" + +func Search(nums []int, target int) int { + lenght := len(nums) + if lenght <= 0 { + return -1 + } + left, right := 0, lenght-1 + + for left <= right { + mid := (right-left)/2 + left + if nums[mid] == target { + return mid + } else if nums[mid] < target { + // ๆ‰พๅณ้‚Š + left = mid + 1 + } else if nums[mid] > target { + // ๆ‰พๅทฆ้‚Š + right = mid - 1 + } + } + // ้ƒฝๆฒ’ๆ‰พๅˆฐ + return -1 +} + +func Search2(nums []int, target int) int { + lenght := len(nums) + if lenght <= 0 { + return -1 + } + left, right := 0, lenght-1 + + for left <= right { + // ้™คไปฅ2 + // mid := left + (right-left)>>1 + mid := int(uint(right+left) >> 1) + if nums[mid] == target { + return mid + } else if nums[mid] < target { + // ๆ‰พๅณ้‚Š + left = mid + 1 + } else if nums[mid] > target { + // ๆ‰พๅทฆ้‚Š + right = mid - 1 + } + } + // ้ƒฝๆฒ’ๆ‰พๅˆฐ + return -1 +} + +// ๅ…งๅปบsort +func BinarySearch(nums []int, target int) int { + length := len(nums) + + index := sort.Search(length, func(i int) bool { + return nums[i] >= target + }) + + if index < length && nums[index] == target { + return index + } else { + return -1 + } +} + +// ไฝฟ็”จ้ž่ฟด +func BinarySearchRecur(nums []int, target int) (index int) { + return BinarySearchRecursively(nums, target, 0, len(nums)-1) +} + +func BinarySearchRecursively(nums []int, target int, start int, end int) int { + if end < start { + return -1 + } + + middle := int(uint(end+start) >> 1) + + if nums[middle] == target { + return middle + } else if target > nums[middle] { + return BinarySearchRecursively(nums, target, middle+1, end) + } else { + return BinarySearchRecursively(nums, target, start, middle-1) + } +} + +// ๆœ‰้ปž้กžไผผ nums ๅฐๆ–ผ target็š„ๅ…ƒ็ด ๆœ‰ๅนพๅ€‹ +func LeftBound(nums []int, target int) (index int) { + lenght := len(nums) + if lenght <= 0 { + return -1 + } + left, right := 0, lenght-1 + + for left <= right { + // ้™คไปฅ2 + // mid := left + (right-left)>>1 + mid := int(uint(right+left) >> 1) + if nums[mid] == target { + // ่ฆ็นผ็บŒๆ‰พๅทฆ้‚Š, ๆ‰€ไปฅๆŠŠๅณ้‚Š่ฎŠๅฐ + right = mid - 1 + } else if nums[mid] < target { + // ๆ‰พๅณ้‚Š + left = mid + 1 + } else if nums[mid] > target { + // ๆ‰พๅทฆ้‚Š + right = mid - 1 + } + } + // ้ƒฝๆฒ’ๆ‰พๅˆฐ ๆณจๆ„: left่ถŠ็•Œๆƒ…ๆณ + if left >= lenght || nums[left] != target { + return -1 + } + return left +} + +func RightBound(nums []int, target int) (index int) { + lenght := len(nums) + if lenght <= 0 { + return -1 + } + left, right := 0, lenght-1 + + for left <= right { + // ้™คไปฅ2 + // mid := left + (right-left)>>1 + mid := int(uint(right+left) >> 1) + if nums[mid] == target { + // ๆณจๆ„:่ฆ็นผ็บŒๆ‰พๅณ้‚Š, ๆ‰€ไปฅๆŠŠๅทฆ้‚Š่ฎŠๅคง=mid+1 + left = mid + 1 + } else if nums[mid] < target { + // ๆ‰พๅณ้‚Š + left = mid + 1 + } else if nums[mid] > target { + // ๆ‰พๅทฆ้‚Š + right = mid - 1 + } + } + // ้ƒฝๆฒ’ๆ‰พๅˆฐ ๆณจๆ„:right่ถŠ็•Œๆƒ…ๆณ + if right < 0 || nums[right] != target { + return -1 + } + return right +} diff --git a/Leetcode/0704.Binary-Search/main_test.go b/Leetcode/0704.Binary-Search/main_test.go new file mode 100644 index 000000000..4034282e0 --- /dev/null +++ b/Leetcode/0704.Binary-Search/main_test.go @@ -0,0 +1,156 @@ +package binarysearch + +import "testing" + +var tests = []struct { + arg1 []int + arg2 int + want int +}{ + { + []int{-1, 0, 3, 5, 9, 12}, + 9, + 4, + }, + { + []int{-1, 0, 3, 5, 9, 12}, + 2, + -1, + }, + { + []int{-1, 0, 3, 5, 9, 12}, + 13, + -1, + }, +} + +var leftboundtests = []struct { + arg1 []int + arg2 int + want int +}{ + { + []int{1, 2, 2, 2, 3}, + 2, + 1, + }, + { + []int{2, 3, 5, 7}, + 1, + -1, + }, + { + []int{2, 3, 5, 7}, + 8, + -1, + }, +} + +var rightboundtests = []struct { + arg1 []int + arg2 int + want int +}{ + { + []int{1, 2, 2, 4}, + 2, + 2, + }, + { + []int{1, 2, 2, 4}, + 0, + -1, + }, + { + []int{2, 3, 5, 7}, + 7, + 3, + }, +} + +func TestSearch(t *testing.T) { + for _, tt := range tests { + if got := Search(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestSearch2(t *testing.T) { + for _, tt := range tests { + if got := Search2(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestLeftBound(t *testing.T) { + for _, tt := range leftboundtests { + if got := LeftBound(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestRightBound(t *testing.T) { + for _, tt := range rightboundtests { + if got := RightBound(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestBinarySearch(t *testing.T) { + for _, tt := range tests { + if got := BinarySearch(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestBinarySearchRecur(t *testing.T) { + for _, tt := range tests { + if got := BinarySearchRecur(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkSearch(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Search(tests[0].arg1, tests[0].arg2) + } +} +func BenchmarkSearch2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + Search2(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkBinarySearch(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + BinarySearch(tests[0].arg1, tests[0].arg2) + } +} + +func BenchmarkBinarySearchRecur(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + BinarySearchRecur(tests[0].arg1, tests[0].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0704.Binary-Search -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0704.Binary-Search +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkSearch-4 365892498 3.483 ns/op 0 B/op 0 allocs/op +BenchmarkSearch2-4 405742570 2.734 ns/op 0 B/op 0 allocs/op +BenchmarkBinarySearch-4 81949826 13.15 ns/op 0 B/op 0 allocs/op +BenchmarkBinarySearchRecur-4 253851086 4.588 ns/op 0 B/op 0 allocs/op +*/ diff --git a/Leetcode/0721.Accounts-Merge/Accounts-Merge.go b/Leetcode/0721.Accounts-Merge/Accounts-Merge.go new file mode 100644 index 000000000..18047065b --- /dev/null +++ b/Leetcode/0721.Accounts-Merge/Accounts-Merge.go @@ -0,0 +1,150 @@ +package accountsmerge + +import ( + "LeetcodeGolang/template" + "sort" +) + +// TODO: ๅ„ชๅŒ– +func AccountsMerge(accounts [][]string) (result [][]string) { + // result := [][]string{} + emailToIndex := map[string]int{} + emailToName := map[string]string{} + indexToEmails := map[int][]string{} + + for _, account := range accounts { + name := account[0] + for _, email := range account[1:] { + if _, has := emailToIndex[email]; !has { + // ็ด€้Œ„ email, ๅฐๅฏซๅ…ฅๅˆฐ ๅฐๆ‡‰็š„index ่ทŸ ๅฐๆ‡‰็š„user name + emailToIndex[email] = len(emailToIndex) + emailToName[email] = name + } + } + } + parent := make([]int, len(emailToIndex)) + // ๅˆๅง‹ๅŒ– + for i := range parent { + parent[i] = i + } + var find func(int) int + find = func(x int) int { + if parent[x] != x { + // ้ž่ฟดไธ€็›ดๆ‰พไธ‹ๅŽป + parent[x] = find(parent[x]) + } + return parent[x] + } + union := func(from, to int) { + parent[find(from)] = find(to) + } + + for _, account := range accounts { + firstIndex := emailToIndex[account[1]] + for _, email := range account[2:] { + union(emailToIndex[email], firstIndex) + } + } + + for email, index := range emailToIndex { + index = find(index) + indexToEmails[index] = append(indexToEmails[index], email) + } + for _, emails := range indexToEmails { + for i := 0; i < len(indexToEmails); i++ { + // fmt.Println(emailToName[indexToEmails[i][0]]) + } + sort.Strings(emails) + account := append([]string{emailToName[emails[0]]}, emails...) + result = append(result, account) + } + + return +} + +func AccountsMerge2(accounts [][]string) (r [][]string) { + uf := template.UnionFind{} + uf.Init(len(accounts)) + // emailToID ๅฐ‡ๆ‰€ๆœ‰็š„ email ้ƒฝๆ‹†้–‹๏ผŒๆ‹†้–‹่ˆ‡ id(ๆ•ธ็ต„ไธ‹ๆจ™) ๅฐๆ‡‰ + // idToName ๅฐ‡ id(ๆ•ธ็ต„ไธ‹ๆจ™) ่ˆ‡ name ๅฐๆ‡‰ + // idToEmails ๅฐ‡ id(ๆ•ธ็ต„ไธ‹ๆจ™) ่ˆ‡ๆ•ด็†ๅฅฝๅŽป้‡ไปฅๅพŒ็š„ email ็ต„ๅฐๆ‡‰ + emailToID, idToName, idToEmails, res := make(map[string]int), make(map[int]string), make(map[int][]string), [][]string{} + for id, acc := range accounts { + idToName[id] = acc[0] + for i := 1; i < len(acc); i++ { + pid, ok := emailToID[acc[i]] + if ok { + uf.Union(id, pid) + } + emailToID[acc[i]] = id + } + } + for email, id := range emailToID { + pid := uf.Find(id) + idToEmails[pid] = append(idToEmails[pid], email) + } + for id, emails := range idToEmails { + name := idToName[id] + sort.Strings(emails) + res = append(res, append([]string{name}, emails...)) + } + return res +} + +// ๆšดๅŠ›่งฃ : Union Find, ็ตๆžœๆฏ”่ผƒๅฟซ +func AccountsMergeBurst(accounts [][]string) [][]string { + if len(accounts) == 0 { + return [][]string{} + } + uf, result, visited := template.UnionFind{}, [][]string{}, map[int]bool{} + uf.Init(len(accounts)) + for i := 0; i < len(accounts); i++ { + for j := i + 1; j < len(accounts); j++ { + if accounts[i][0] == accounts[j][0] { + // A, Bๅธณ่™Ÿ. ๅๅญ—ไธ€ๆจฃ + tmpAmail, tmpBmail, flag := accounts[i][1:], accounts[j][1:], false + for j := 0; j < len(tmpAmail); j++ { + for k := 0; k < len(tmpBmail); k++ { + if tmpAmail[j] == tmpBmail[k] { + // A,B ๅธณ่™Ÿ, ๆ‰พๅˆฐ็›ธๅŒ็š„email. ่ชๅฎš็‚บๅŒไธ€ไบบ + flag = true + break + } + } + if flag { + break + } + } + if flag { + uf.Union(i, j) + } + } + } + } + for i := 0; i < len(accounts); i++ { + if visited[i] { + continue + } + emails, account, tmpMap := accounts[i][1:], []string{accounts[i][0]}, map[string]string{} + for j := i + 1; j < len(accounts); j++ { + if uf.Find(j) == uf.Find(i) { + visited[j] = true + for _, v := range accounts[j][1:] { + tmpMap[v] = v + } + } + } + // A ๅธณ่™Ÿ Email + for _, v := range emails { + tmpMap[v] = v + } + emails = []string{} + for key := range tmpMap { + emails = append(emails, key) + } + sort.Strings(emails) + account = append(account, emails...) + result = append(result, account) + } + return result +} diff --git a/Leetcode/0721.Accounts-Merge/Accounts-Merge_test.go b/Leetcode/0721.Accounts-Merge/Accounts-Merge_test.go new file mode 100644 index 000000000..3e3b78ac0 --- /dev/null +++ b/Leetcode/0721.Accounts-Merge/Accounts-Merge_test.go @@ -0,0 +1,103 @@ +package accountsmerge + +import ( + "fmt" + "testing" +) + +var tests = []struct { + arg1 [][]string + want [][]string +}{ + { + [][]string{ + {"John", "johnsmith@mail.com", "john00@mail.com"}, + {"John", "johnnybravo@mail.com"}, + {"John", "johnsmith@mail.com", "john_newyork@mail.com"}, + {"Mary", "mary@mail.com"}, + }, + [][]string{ + {"John", "john00@mail.com", "john_newyork@mail.com", "johnsmith@mail.com"}, + {"John", "johnnybravo@mail.com"}, + {"Mary", "mary@mail.com"}, + }, + }, + { + [][]string{ + {"Alex", "Alex5@m.co", "Alex4@m.co", "Alex0@m.co"}, + {"Ethan", "Ethan3@m.co", "Ethan3@m.co", "Ethan0@m.co"}, + {"Kevin", "Kevin4@m.co", "Kevin2@m.co", "Kevin2@m.co"}, + {"Gabe", "Gabe0@m.co", "Gabe3@m.co", "Gabe2@m.co"}, + {"Gabe", "Gabe3@m.co", "Gabe4@m.co", "Gabe2@m.co"}, + }, + [][]string{ + {"Alex", "Alex0@m.co", "Alex4@m.co", "Alex5@m.co"}, + {"Ethan", "Ethan0@m.co", "Ethan3@m.co"}, + {"Kevin", "Kevin2@m.co", "Kevin4@m.co"}, + {"Gabe", "Gabe0@m.co", "Gabe2@m.co", "Gabe3@m.co", "Gabe4@m.co"}, + }, + }, + { + [][]string{ + {"David", "David0@m.co", "David4@m.co", "David3@m.co"}, + {"David", "David5@m.co", "David5@m.co", "David0@m.co"}, + {"David", "David1@m.co", "David4@m.co", "David0@m.co"}, + {"David", "David0@m.co", "David1@m.co", "David3@m.co"}, + {"David", "David4@m.co", "David1@m.co", "David3@m.co"}, + }, + [][]string{ + {"David", "David0@m.co", "David1@m.co", "David3@m.co", "David4@m.co", "David5@m.co"}, + }, + }, + { + [][]string{}, + [][]string{}, + }, +} + +func TestAccountsMergeBurst(t *testing.T) { + for _, tt := range tests { + // if got := AccountsMergeBurst(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // t.Errorf("got = %v \n want = %v \n", tt.arg1, tt.want) + // } + fmt.Printf("ใ€inputใ€‘: \n%v \nใ€outputใ€‘:\n%v \n", tt.arg1, AccountsMergeBurst(tt.arg1)) + } +} + +func TestAccountsMerge(t *testing.T) { + for _, tt := range tests { + // if got := AccountsMerge(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // t.Errorf("got = %v \n want = %v \n", tt.arg1, tt.want) + // } + fmt.Printf("\nใ€inputใ€‘: \n%v \nใ€outputใ€‘:\n%v \n", tt.arg1, AccountsMerge(tt.arg1)) + } +} + +func BenchmarkAccountsMergeBurst(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + AccountsMergeBurst(tests[1].arg1) + } +} + +func BenchmarkAccountsMerge(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + AccountsMerge(tests[1].arg1) + } +} + +func BenchmarkAccountsMerge2(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + AccountsMerge2(tests[1].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0721.Accounts-Merge -bench=. +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkAccountsMergeBurst-8 394038 2885 ns/op 984 B/op 27 allocs/op +BenchmarkAccountsMerge-8 240194 5594 ns/op 2008 B/op 28 allocs/op +BenchmarkAccountsMerge2-8 315127 3755 ns/op 1413 B/op 28 allocs/op +*/ diff --git a/Leetcode/0721.Accounts-Merge/index.html b/Leetcode/0721.Accounts-Merge/index.html new file mode 100644 index 000000000..7991d7d4a --- /dev/null +++ b/Leetcode/0721.Accounts-Merge/index.html @@ -0,0 +1,3991 @@ + + + + + + + 0721.Accounts Merge ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                              721. Accounts Merge

                                                                                                                                                                                                                              题目

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emailsrepresenting emails of the account.

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name.

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              Example 1:

                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              Input: 
                                                                                                                                                                                                                              +accounts = [["John", "johnsmith@mail.com", "john00@mail.com"], ["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com", "john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
                                                                                                                                                                                                                              +Output: [["John", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'],  ["John", "johnnybravo@mail.com"], ["Mary", "mary@mail.com"]]
                                                                                                                                                                                                                              +Explanation: 
                                                                                                                                                                                                                              +The first and third John's are the same person as they have the common email "johnsmith@mail.com".
                                                                                                                                                                                                                              +The second John and Mary are different people as none of their email addresses are used by other accounts.
                                                                                                                                                                                                                              +We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], 
                                                                                                                                                                                                                              +['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted.
                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              Note:

                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                              • The length of accounts will be in the range [1, 1000].
                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                              • The length of accounts[i] will be in the range [1, 10].
                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                              • The length of accounts[i][j] will be in the range [1, 30].
                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              題目大意

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              給定一個列表 accounts,每個元素 accounts[i] 是一個字符串列表,其中第一個元素 accounts[i][0] 是 名稱 (name),其餘元素是 emails 表示該賬戶的郵箱地址。 現在,我們想合併這些賬戶。如果兩個賬戶都有一些共同的郵箱地址,則兩個賬戶必定屬於同一個人。請注意,即使兩個賬戶具有相同的名稱,它們也可能屬於不同的人,因為人們可能具有相同的名稱。一個人最初可以擁有任意數量的賬戶,但其所有賬戶都具有相同的名稱。 合併賬戶後,按以下格式返回賬戶:每個賬戶的第一個元素是名稱,其餘元素是按字符 ASCII 順序排列的郵箱地址。賬戶本身可以以任意順序返回。

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              解題思路

                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                              • 給出一堆賬戶和對應的郵箱。要求合併同一個人的多個郵箱賬戶。
                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                              • 如果這個人名和所屬的其中之一的郵箱是相同的,就判定這是同一個人的郵箱,那麼就合併這些郵箱。
                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                              • 這題的解題思路是並查集。不過如果用暴力合併的方法,時間複雜度非常差。優化方法是先把每組數據都進行編號,人編號,每個郵箱都進行編號。這個映射關係用 map 記錄起來。如果利用並查集的 union() 操作,把這些編號都進行合併。最後把人的編號和對應郵箱的編號拼接起來。
                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                              • 這一題有 2 處比較“坑”的是,不需要合併的用戶的郵箱列表也是需要排序和去重的,同一個人的所有郵箱集合都要合併到一起。具體見測試用例。不過題目中也提到了這些點,也不能算題目坑,只能歸自己沒注意這些邊界情況。
                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              來源

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0721.Accounts-Merge/

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              時間複雜度:O(n log n)

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              其中 n 是不同郵箱地址的數量。 +需要遍歷所有郵箱地址,在並查集內進行查找和合併操作,對於兩個不同的郵箱地址, +如果它們的祖先不同則需要進行合併,需要進行 2 次查找和最多 1 次合併。一共需要進行 2n 次查找和最多 n 次合併, +因此時間複雜度是 O(2n log n) = O(n log n)。 +這裡的並查集使用了路徑壓縮,但是沒有使用按秩合併, +最壞情況下的時間複雜度是O(n log n),平均情況下的時間複雜度依然是 O(nα(n)),其中α 為阿克曼函數的反函數,α(n) 可以認為是一個很小的常數。 +整理出題目要求的返回賬戶的格式時需要對郵箱地址排序,時間複雜度是 O(n log n)。 +其餘操作包括遍歷所有郵箱地址,在哈希表中記錄相應的信息,時間複雜度是O(n), +在漸進意義下O(n) 小於O(nlog n)。 +因此總時間複雜度是 O(n log n)。

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              作者:LeetCode-Solution +鏈接:https://leetcode-cn.com/problems/accounts-merge/solution/zhang-hu-he-bing-by-leetcode-solution-3dyq/ +來源:力扣(LeetCode) +著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              來源

                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                              解答

                                                                                                                                                                                                                              +

                                                                                                                                                                                                                              https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0721.Accounts-Merge/Accounts-Merge.go

                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              package accountsmerge
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +import (
                                                                                                                                                                                                                              +    "LeetcodeGolang/template"
                                                                                                                                                                                                                              +    "sort"
                                                                                                                                                                                                                              +)
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +// TODO: 優化
                                                                                                                                                                                                                              +func AccountsMerge(accounts [][]string) (result [][]string) {
                                                                                                                                                                                                                              +    // result := [][]string{}
                                                                                                                                                                                                                              +    emailToIndex := map[string]int{}
                                                                                                                                                                                                                              +    emailToName := map[string]string{}
                                                                                                                                                                                                                              +    indexToEmails := map[int][]string{}
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +    for _, account := range accounts {
                                                                                                                                                                                                                              +        name := account[0]
                                                                                                                                                                                                                              +        for _, email := range account[1:] {
                                                                                                                                                                                                                              +            if _, has := emailToIndex[email]; !has {
                                                                                                                                                                                                                              +                // 紀錄 email, 對寫入到 對應的index 跟 對應的user name
                                                                                                                                                                                                                              +                emailToIndex[email] = len(emailToIndex)
                                                                                                                                                                                                                              +                emailToName[email] = name
                                                                                                                                                                                                                              +            }
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    parent := make([]int, len(emailToIndex))
                                                                                                                                                                                                                              +    // 初始化
                                                                                                                                                                                                                              +    for i := range parent {
                                                                                                                                                                                                                              +        parent[i] = i
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    var find func(int) int
                                                                                                                                                                                                                              +    find = func(x int) int {
                                                                                                                                                                                                                              +        if parent[x] != x {
                                                                                                                                                                                                                              +            // 遞迴一直找下去
                                                                                                                                                                                                                              +            parent[x] = find(parent[x])
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +        return parent[x]
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    union := func(from, to int) {
                                                                                                                                                                                                                              +        parent[find(from)] = find(to)
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +    for _, account := range accounts {
                                                                                                                                                                                                                              +        firstIndex := emailToIndex[account[1]]
                                                                                                                                                                                                                              +        for _, email := range account[2:] {
                                                                                                                                                                                                                              +            union(emailToIndex[email], firstIndex)
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +    for email, index := range emailToIndex {
                                                                                                                                                                                                                              +        index = find(index)
                                                                                                                                                                                                                              +        indexToEmails[index] = append(indexToEmails[index], email)
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    for _, emails := range indexToEmails {
                                                                                                                                                                                                                              +        for i := 0; i < len(indexToEmails); i++ {
                                                                                                                                                                                                                              +            // fmt.Println(emailToName[indexToEmails[i][0]])
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +        sort.Strings(emails)
                                                                                                                                                                                                                              +        account := append([]string{emailToName[emails[0]]}, emails...)
                                                                                                                                                                                                                              +        result = append(result, account)
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +    return
                                                                                                                                                                                                                              +}
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +func AccountsMerge2(accounts [][]string) (r [][]string) {
                                                                                                                                                                                                                              +    uf := template.UnionFind{}
                                                                                                                                                                                                                              +    uf.Init(len(accounts))
                                                                                                                                                                                                                              +    // emailToID 將所有的 email 都拆開,拆開與 id(數組下標) 對應
                                                                                                                                                                                                                              +    // idToName 將 id(數組下標) 與 name 對應
                                                                                                                                                                                                                              +    // idToEmails 將 id(數組下標) 與整理好去重以後的 email 組對應
                                                                                                                                                                                                                              +    emailToID, idToName, idToEmails, res := make(map[string]int), make(map[int]string), make(map[int][]string), [][]string{}
                                                                                                                                                                                                                              +    for id, acc := range accounts {
                                                                                                                                                                                                                              +        idToName[id] = acc[0]
                                                                                                                                                                                                                              +        for i := 1; i < len(acc); i++ {
                                                                                                                                                                                                                              +            pid, ok := emailToID[acc[i]]
                                                                                                                                                                                                                              +            if ok {
                                                                                                                                                                                                                              +                uf.Union(id, pid)
                                                                                                                                                                                                                              +            }
                                                                                                                                                                                                                              +            emailToID[acc[i]] = id
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    for email, id := range emailToID {
                                                                                                                                                                                                                              +        pid := uf.Find(id)
                                                                                                                                                                                                                              +        idToEmails[pid] = append(idToEmails[pid], email)
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    for id, emails := range idToEmails {
                                                                                                                                                                                                                              +        name := idToName[id]
                                                                                                                                                                                                                              +        sort.Strings(emails)
                                                                                                                                                                                                                              +        res = append(res, append([]string{name}, emails...))
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    return res
                                                                                                                                                                                                                              +}
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +// 暴力解 : Union Find, 結果比較快
                                                                                                                                                                                                                              +func AccountsMergeBurst(accounts [][]string) [][]string {
                                                                                                                                                                                                                              +    if len(accounts) == 0 {
                                                                                                                                                                                                                              +        return [][]string{}
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    uf, result, visited := template.UnionFind{}, [][]string{}, map[int]bool{}
                                                                                                                                                                                                                              +    uf.Init(len(accounts))
                                                                                                                                                                                                                              +    for i := 0; i < len(accounts); i++ {
                                                                                                                                                                                                                              +        for j := i + 1; j < len(accounts); j++ {
                                                                                                                                                                                                                              +            if accounts[i][0] == accounts[j][0] {
                                                                                                                                                                                                                              +                // A, B帳號. 名字一樣
                                                                                                                                                                                                                              +                tmpAmail, tmpBmail, flag := accounts[i][1:], accounts[j][1:], false
                                                                                                                                                                                                                              +                for j := 0; j < len(tmpAmail); j++ {
                                                                                                                                                                                                                              +                    for k := 0; k < len(tmpBmail); k++ {
                                                                                                                                                                                                                              +                        if tmpAmail[j] == tmpBmail[k] {
                                                                                                                                                                                                                              +                            // A,B 帳號, 找到相同的email. 認定為同一人
                                                                                                                                                                                                                              +                            flag = true
                                                                                                                                                                                                                              +                            break
                                                                                                                                                                                                                              +                        }
                                                                                                                                                                                                                              +                    }
                                                                                                                                                                                                                              +                    if flag {
                                                                                                                                                                                                                              +                        break
                                                                                                                                                                                                                              +                    }
                                                                                                                                                                                                                              +                }
                                                                                                                                                                                                                              +                if flag {
                                                                                                                                                                                                                              +                    uf.Union(i, j)
                                                                                                                                                                                                                              +                }
                                                                                                                                                                                                                              +            }
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    for i := 0; i < len(accounts); i++ {
                                                                                                                                                                                                                              +        if visited[i] {
                                                                                                                                                                                                                              +            continue
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +        emails, account, tmpMap := accounts[i][1:], []string{accounts[i][0]}, map[string]string{}
                                                                                                                                                                                                                              +        for j := i + 1; j < len(accounts); j++ {
                                                                                                                                                                                                                              +            if uf.Find(j) == uf.Find(i) {
                                                                                                                                                                                                                              +                visited[j] = true
                                                                                                                                                                                                                              +                for _, v := range accounts[j][1:] {
                                                                                                                                                                                                                              +                    tmpMap[v] = v
                                                                                                                                                                                                                              +                }
                                                                                                                                                                                                                              +            }
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +        // A 帳號 Email
                                                                                                                                                                                                                              +        for _, v := range emails {
                                                                                                                                                                                                                              +            tmpMap[v] = v
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +        emails = []string{}
                                                                                                                                                                                                                              +        for key := range tmpMap {
                                                                                                                                                                                                                              +            emails = append(emails, key)
                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                              +        sort.Strings(emails)
                                                                                                                                                                                                                              +        account = append(account, emails...)
                                                                                                                                                                                                                              +        result = append(result, account)
                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                              +    return result
                                                                                                                                                                                                                              +}
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              +
                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                              results matching ""

                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                + +

                                                                                                                                                                                                                                No results matching ""

                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                + + + + + + +
                                                                                                                                                                                                                                + + +
                                                                                                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0733.Flood-Fill/images/flood1-grid.jpg b/Leetcode/0733.Flood-Fill/images/flood1-grid.jpg new file mode 100644 index 000000000..bd7ba981e Binary files /dev/null and b/Leetcode/0733.Flood-Fill/images/flood1-grid.jpg differ diff --git a/Leetcode/0733.Flood-Fill/index.html b/Leetcode/0733.Flood-Fill/index.html new file mode 100644 index 000000000..68e440da5 --- /dev/null +++ b/Leetcode/0733.Flood-Fill/index.html @@ -0,0 +1,3942 @@ + + + + + + + 0733.Flood Fill ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                + +

                                                                                                                                                                                                                                0733.Flood Fill

                                                                                                                                                                                                                                題目

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                You are also given three integers sr,sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                Return the modified image after performing the flood fill.

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                Example 1: +

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
                                                                                                                                                                                                                                +Output: [[2,2,2],[2,2,0],[2,0,1]]
                                                                                                                                                                                                                                +Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
                                                                                                                                                                                                                                +Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                Example 2:

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
                                                                                                                                                                                                                                +Output: [[0,0,0],[0,0,0]]
                                                                                                                                                                                                                                +Explanation: The starting pixel is already colored 0, so no changes are made to the image.
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                Constraints:

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                • m == image.length
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                • n == image[i].length
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                • 1 <= m, n <= 50
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                • 0 <= image[i][j], color < 216
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                • 0 <= sr < m
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                • 0 <= sc < n
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                題目大意

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                有一個以二維整數陣列表示的圖畫,每個整數表示該圖畫的像素值大小,數值在 0 到 65535 之間。 +給你一個坐標 (sr, sc) 表示圖像渲染開始的像素值(行 ,列)和一個新的顏色值新顏色,讓您重新上色該幅圖像。

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                為了完成上顏色工作,從主板坐標開始,記錄主板坐標的上下四個方向上像素值與主板坐標相同的完整像素點,連接再記錄這四個方向上條件符合的像素點與它們對應的四個像素點方向上像素值與主板坐標的連通像素點相同,……,重複該過程。將所有有記錄的像素點的顏色值改為新的顏色值。最後返回經過上顏色渲染後的圖像。

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                注意:

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                • image 和 image[0] 的長度在範圍 [1, 50] 內。
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                • 給出的初始點將滿足 0 <= sr < image.length 和 0 <= sc < image[0].length。
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                • image[i][j] 和 newColor 表示的顏色值在範圍 [0, 65535] 內。
                                                                                                                                                                                                                                • +
                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                解題思路

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                一個給出二維的圖片點陣,每個點陣都有一個數字。給出起點一個坐標,要求從這個起點坐標開始,把所有與這個起點設置的點都染色成新的顏色。 +這題是標準的洪水填充算法。可以用 DFS 也可以用 BFS 。

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                BFS比較適合找最短路徑,DFS比較適合找所有路徑 +DFS使用遞迴比較好寫

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                使用DFS的解法:

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                1. 檢查起始點的顏色是否等於新的顏色,如果是則直接返回圖像。
                                                                                                                                                                                                                                2. +
                                                                                                                                                                                                                                3. 呼叫深度優先搜索函數dfs,傳入起始點座標sr和sc。
                                                                                                                                                                                                                                4. +
                                                                                                                                                                                                                                5. 在dfs函數中,檢查當前座標的顏色是否等於起始點的顏色,如果是則將其顏色修改為新的顏色。
                                                                                                                                                                                                                                6. +
                                                                                                                                                                                                                                7. 遞迴地對當前座標的四個相鄰方格進行dfs。
                                                                                                                                                                                                                                8. +
                                                                                                                                                                                                                                9. 返回填充完成的圖像。
                                                                                                                                                                                                                                10. +
                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                時間複雜度: 圖像中的每個方格最多被訪問一次,因此時間複雜度為O(mn),其中m和n分別為圖像的行數和列數。 +空間複雜度: 使用了遞迴調用的栈空間,空間複雜度為O(mn)。

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                使用BFS的解題思路如下:

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                1. 檢查起始點的顏色是否等於新的顏色,如果是則直接返回圖像。
                                                                                                                                                                                                                                2. +
                                                                                                                                                                                                                                3. 創建一個隊列,將起始點的座標(sr, sc)加入隊列中。
                                                                                                                                                                                                                                4. +
                                                                                                                                                                                                                                5. 創建一個訪問過的集合,將起始點的座標(sr, sc)添加到集合中,表示已經訪問過。
                                                                                                                                                                                                                                6. +
                                                                                                                                                                                                                                7. 進入BFS循環,當隊列不為空時,執行以下操作:
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                  • 從隊列中取出一個座標(current_r, current_c)。
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • 檢查該座標的顏色是否等於起始點的顏色,如果是,將該座標的顏色修改為新的顏色。
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • 檢查該座標的四個相鄰方格,如果相鄰方格的座標有效且顏色等於起始點的顏色,且該相鄰方格的座標還沒有被訪問過,則將該相鄰方格的座標加入隊列中,同時將該相鄰方格的座標添加到訪問過的集合中。
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • 重複以上步驟,直到隊列為空。
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                8. +
                                                                                                                                                                                                                                9. 返回填充完成的圖像。
                                                                                                                                                                                                                                10. +
                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                時間複雜度和空間複雜度的分析與DFS解法相同。 +使用BFS的解法同樣可以完成泛洪填充的任務,不同的是使用隊列來保存待處理的座標,而不是使用遞迴函數。

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                來源

                                                                                                                                                                                                                                + +

                                                                                                                                                                                                                                解答

                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0733.Flood-Fill/main.go

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                package floodfill
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +// DFS
                                                                                                                                                                                                                                +func FloodFill(image [][]int, sr int, sc int, color int) [][]int {
                                                                                                                                                                                                                                +    oldColor := image[sr][sc]
                                                                                                                                                                                                                                +    if color == oldColor {
                                                                                                                                                                                                                                +        return image
                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                +    dfsfill(image, sr, sc, oldColor, color)
                                                                                                                                                                                                                                +    return image
                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +func dfsfill(image [][]int, row, col, oldColor, newColor int) {
                                                                                                                                                                                                                                +    // Check if the current pixel is out of bounds or does not have the old color
                                                                                                                                                                                                                                +    if row < 0 || row >= len(image) || col < 0 || col >= len(image[0]) || image[row][col] != oldColor {
                                                                                                                                                                                                                                +        return
                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +    // Update the current pixel with the new color
                                                                                                                                                                                                                                +    image[row][col] = newColor
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +    // Recursively perform flood fill on the adjacent pixels
                                                                                                                                                                                                                                +    dfsfill(image, row-1, col, oldColor, newColor) // Up
                                                                                                                                                                                                                                +    dfsfill(image, row+1, col, oldColor, newColor) // Down
                                                                                                                                                                                                                                +    dfsfill(image, row, col-1, oldColor, newColor) // Left
                                                                                                                                                                                                                                +    dfsfill(image, row, col+1, oldColor, newColor) // Right
                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +type Point struct {
                                                                                                                                                                                                                                +    row, col int
                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +func FloodFillBFS(image [][]int, sr int, sc int, newColor int) [][]int {
                                                                                                                                                                                                                                +    // Check if the starting point is out of bounds or already has the new color
                                                                                                                                                                                                                                +    if sr < 0 || sr >= len(image) || sc < 0 || sc >= len(image[0]) || image[sr][sc] == newColor {
                                                                                                                                                                                                                                +        return image
                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +    // Get the old color at the starting point
                                                                                                                                                                                                                                +    oldColor := image[sr][sc]
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +    // Create a queue and enqueue the starting point
                                                                                                                                                                                                                                +    queue := []Point{{sr, sc}}
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +    // Define the directions (up, down, left, right)
                                                                                                                                                                                                                                +    directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +    // Perform BFS
                                                                                                                                                                                                                                +    for len(queue) > 0 {
                                                                                                                                                                                                                                +        // Dequeue a point from the queue
                                                                                                                                                                                                                                +        point := queue[0]
                                                                                                                                                                                                                                +        queue = queue[1:]
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +        // Update the point with the new color
                                                                                                                                                                                                                                +        image[point.row][point.col] = newColor
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +        // Explore the neighboring pixels
                                                                                                                                                                                                                                +        for _, dir := range directions {
                                                                                                                                                                                                                                +            newRow, newCol := point.row+dir[0], point.col+dir[1]
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +            // Check if the neighboring pixel is within bounds and has the old color
                                                                                                                                                                                                                                +            if newRow >= 0 && newRow < len(image) && newCol >= 0 && newCol < len(image[0]) && image[newRow][newCol] == oldColor {
                                                                                                                                                                                                                                +                // Enqueue the neighboring pixel
                                                                                                                                                                                                                                +                queue = append(queue, Point{newRow, newCol})
                                                                                                                                                                                                                                +            }
                                                                                                                                                                                                                                +        }
                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +    return image
                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                Benchmark

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                goos: darwin
                                                                                                                                                                                                                                +goarch: amd64
                                                                                                                                                                                                                                +pkg: LeetcodeGolang/Leetcode/0733.Flood-Fill
                                                                                                                                                                                                                                +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                                                                +BenchmarkFloodFillDFS-8         384756555                4.486 ns/op           0 B/op          0 allocs/op
                                                                                                                                                                                                                                +BenchmarkFloodFillBFS-8         309088303                3.642 ns/op           0 B/op          0 allocs/op
                                                                                                                                                                                                                                +PASS
                                                                                                                                                                                                                                +ok      LeetcodeGolang/Leetcode/0733.Flood-Fill 3.572s
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                + +

                                                                                                                                                                                                                                results matching ""

                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                                  No results matching ""

                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  + + + + + + +
                                                                                                                                                                                                                                  + + +
                                                                                                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0733.Flood-Fill/main.go b/Leetcode/0733.Flood-Fill/main.go new file mode 100644 index 000000000..f637a17b1 --- /dev/null +++ b/Leetcode/0733.Flood-Fill/main.go @@ -0,0 +1,70 @@ +package floodfill + +// DFS +func FloodFill(image [][]int, sr int, sc int, color int) [][]int { + oldColor := image[sr][sc] + if color == oldColor { + return image + } + dfsfill(image, sr, sc, oldColor, color) + return image +} + +func dfsfill(image [][]int, row, col, oldColor, newColor int) { + // Check if the current pixel is out of bounds or does not have the old color + if row < 0 || row >= len(image) || col < 0 || col >= len(image[0]) || image[row][col] != oldColor { + return + } + + // Update the current pixel with the new color + image[row][col] = newColor + + // Recursively perform flood fill on the adjacent pixels + dfsfill(image, row-1, col, oldColor, newColor) // Up + dfsfill(image, row+1, col, oldColor, newColor) // Down + dfsfill(image, row, col-1, oldColor, newColor) // Left + dfsfill(image, row, col+1, oldColor, newColor) // Right +} + +type Point struct { + row, col int +} + +func FloodFillBFS(image [][]int, sr int, sc int, newColor int) [][]int { + // Check if the starting point is out of bounds or already has the new color + if sr < 0 || sr >= len(image) || sc < 0 || sc >= len(image[0]) || image[sr][sc] == newColor { + return image + } + + // Get the old color at the starting point + oldColor := image[sr][sc] + + // Create a queue and enqueue the starting point + queue := []Point{{sr, sc}} + + // Define the directions (up, down, left, right) + directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} + + // Perform BFS + for len(queue) > 0 { + // Dequeue a point from the queue + point := queue[0] + queue = queue[1:] + + // Update the point with the new color + image[point.row][point.col] = newColor + + // Explore the neighboring pixels + for _, dir := range directions { + newRow, newCol := point.row+dir[0], point.col+dir[1] + + // Check if the neighboring pixel is within bounds and has the old color + if newRow >= 0 && newRow < len(image) && newCol >= 0 && newCol < len(image[0]) && image[newRow][newCol] == oldColor { + // Enqueue the neighboring pixel + queue = append(queue, Point{newRow, newCol}) + } + } + } + + return image +} diff --git a/Leetcode/0733.Flood-Fill/main_test.go b/Leetcode/0733.Flood-Fill/main_test.go new file mode 100644 index 000000000..831d0bee9 --- /dev/null +++ b/Leetcode/0733.Flood-Fill/main_test.go @@ -0,0 +1,101 @@ +package floodfill + +import ( + "reflect" + "testing" +) + +var tests = []struct { + image [][]int + sr, sc, color int + expected [][]int +}{ + { + [][]int{ + {1, 1, 1}, + {1, 1, 0}, + {1, 0, 1}, + }, + 1, 1, 2, + [][]int{ + {2, 2, 2}, + {2, 2, 0}, + {2, 0, 1}, + }, + }, + { + [][]int{ + {0, 0, 0}, + {0, 0, 0}, + {0, 0, 0}, + }, + 1, 1, 1, + [][]int{ + {1, 1, 1}, + {1, 1, 1}, + {1, 1, 1}, + }, + }, + { + [][]int{ + {1, 1, 1}, + {1, 1, 1}, + {1, 1, 1}, + }, + 0, 0, 0, + [][]int{ + {0, 0, 0}, + {0, 0, 0}, + {0, 0, 0}, + }, + }, + // Add more test cases here if needed +} + +func TestFloodFillDFS(t *testing.T) { + for _, tt := range tests { + result := FloodFill(tt.image, tt.sr, tt.sc, tt.color) + // Check if the result matches the expected output + if !reflect.DeepEqual(result, tt.expected) { + t.Errorf("FloodFillDFS(%v, %d, %d, %d) returned %+v, expected %+v", + tt.image, tt.sr, tt.sc, tt.color, result, tt.expected) + } + } +} + +func TestFloodFillBFS(t *testing.T) { + for _, tt := range tests { + result := FloodFillBFS(tt.image, tt.sr, tt.sc, tt.color) + // Check if the result matches the expected output + if !reflect.DeepEqual(result, tt.expected) { + t.Errorf("FloodFillBFS(%v, %d, %d, %d) returned %+v, expected %+v", + tt.image, tt.sr, tt.sc, tt.color, result, tt.expected) + } + } +} + +func BenchmarkFloodFillDFS(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FloodFill(tests[0].image, tests[0].sr, tests[0].sc, tests[0].color) + } +} + +func BenchmarkFloodFillBFS(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FloodFillBFS(tests[0].image, tests[0].sr, tests[0].sc, tests[0].color) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0733.Flood-Fill -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0733.Flood-Fill +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkFloodFillDFS-8 384756555 4.486 ns/op 0 B/op 0 allocs/op +BenchmarkFloodFillBFS-8 309088303 3.642 ns/op 0 B/op 0 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0733.Flood-Fill 3.572s +*/ diff --git a/Leetcode/0746.Min-Cost-Climbing-Stairs/index.html b/Leetcode/0746.Min-Cost-Climbing-Stairs/index.html new file mode 100644 index 000000000..818027468 --- /dev/null +++ b/Leetcode/0746.Min-Cost-Climbing-Stairs/index.html @@ -0,0 +1,3952 @@ + + + + + + + 746. Min Cost Climbing Stairs ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                                  746. Min Cost Climbing Stairs

                                                                                                                                                                                                                                  題目

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  You can either start from the step with index 0, or the step with index 1.

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  Return the minimum cost to reach the top of the floor.

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  Example 1:

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  Input: cost = [10,15,20] +Output: 15 +Explanation: You will start at index 1.

                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                  • Pay 15 and climb two steps to reach the top. +The total cost is 15. +Example 2:
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  Input: cost = [1,100,1,1,1,100,1,1,100,1] +Output: 6 +Explanation: You will start at index 0.

                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                  • Pay 1 and climb two steps to reach index 2.
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • Pay 1 and climb two steps to reach index 4.
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • Pay 1 and climb two steps to reach index 6.
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • Pay 1 and climb one step to reach index 7.
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • Pay 1 and climb two steps to reach index 9.
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  • Pay 1 and climb one step to reach the top. +The total cost is 6.
                                                                                                                                                                                                                                  • +
                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  Constraints:

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  2 <= cost.length <= 1000 +0 <= cost[i] <= 999

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  題目大意

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  陣列的每個索引做為一個階梯,第 i 個階梯對應著一個非負數的體力花費值 cost[i] (索引從 0 開始)。 每當你爬上一個階梯你都要花費對應的體力花費值,然後你可以選擇繼續爬一個階梯或者爬兩個階梯。 您需要找到達到樓層頂部的最低花費。 在開始時,你可以選擇從索引為 0 或 1 的元素作為初始階梯。

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  解題思路

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  cur 變數存儲從第 i-2 步到達第 i 步的最小花費。 +last 變數存儲從第 i-1 步到達第 i 步的最小花費。 +在每次迭代中,函數都會比較 cur 和 last 變數的值,並選擇較小的那個存儲在 cur 變數中。 +在迭代結束時,last 變數將存儲爬完所有樓梯的最小花費。

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  cost := []int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}

                                                                                                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                  迭代curlast
                                                                                                                                                                                                                                  201
                                                                                                                                                                                                                                  312
                                                                                                                                                                                                                                  422
                                                                                                                                                                                                                                  523
                                                                                                                                                                                                                                  633
                                                                                                                                                                                                                                  734
                                                                                                                                                                                                                                  844
                                                                                                                                                                                                                                  945
                                                                                                                                                                                                                                  1056
                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  Big O

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  時間複雜 : O(n) +空間複雜 : O(1)

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  來源

                                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                                  解答

                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0746.Min-Cost-Climbing-Stairs/main.go

                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  package mincostclimbingstairs
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  +// 時間複雜 O(n), 空間複雜 O(1)
                                                                                                                                                                                                                                  +func MinCostClimbingStairs(cost []int) int {
                                                                                                                                                                                                                                  +    dp := make([]int, len(cost))
                                                                                                                                                                                                                                  +    dp[0], dp[1] = cost[0], cost[1]
                                                                                                                                                                                                                                  +    for i := 2; i < len(cost); i++ {
                                                                                                                                                                                                                                  +        dp[i] = cost[i] + min(dp[i-1], dp[i-2])
                                                                                                                                                                                                                                  +    }
                                                                                                                                                                                                                                  +    return min(dp[len(cost)-2], dp[len(cost)-1])
                                                                                                                                                                                                                                  +}
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  +func min(a, b int) int {
                                                                                                                                                                                                                                  +    if a > b {
                                                                                                                                                                                                                                  +        return b
                                                                                                                                                                                                                                  +    }
                                                                                                                                                                                                                                  +    return a
                                                                                                                                                                                                                                  +}
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  +// 時間複雜 O(n), 空間複雜 O(1)
                                                                                                                                                                                                                                  +// 優化
                                                                                                                                                                                                                                  +// 使用了兩個變數cur和last,
                                                                                                                                                                                                                                  +// cur 變數存儲從第 i-2 步到達第 i 步的最小花費。
                                                                                                                                                                                                                                  +// last 變數存儲從第 i-1 步到達第 i 步的最小花費。
                                                                                                                                                                                                                                  +// 比較兩種選擇的花費:
                                                                                                                                                                                                                                  +// 從第2階開始(i := 2),一直迭代到最後一階(i < len(cost)+1)。
                                                                                                                                                                                                                                  +// 在每一步驟中:
                                                                                                                                                                                                                                  +// 比較兩種選擇的花費:
                                                                                                                                                                                                                                  +//
                                                                                                                                                                                                                                  +//    選擇從上一階跳到當前階的花費:last + cost[i-1]
                                                                                                                                                                                                                                  +//    選擇從上上階跳到當前階的花費:cur + cost[i-2]
                                                                                                                                                                                                                                  +//
                                                                                                                                                                                                                                  +// 選擇花費較小的方案:
                                                                                                                                                                                                                                  +//
                                                                                                                                                                                                                                  +//    如果 last + cost[i-1] 更小,則將 last 的值更新為 cur + cost[i-2],並將 cur 的值更新為 last(即上一步的最小花費)。
                                                                                                                                                                                                                                  +//    否則,將 last 的值更新為 last + cost[i-1],並將 cur 的值更新為 last(即上一步的最小花費)。
                                                                                                                                                                                                                                  +func MinCostClimbingStairsOptimize(cost []int) int {
                                                                                                                                                                                                                                  +    var cur, last int
                                                                                                                                                                                                                                  +    for i := 2; i < len(cost)+1; i++ {
                                                                                                                                                                                                                                  +        // 選擇從上一階跳到當前階的花費:last + cost[i-1]
                                                                                                                                                                                                                                  +        // 選擇從上上階跳到當前階的花費:cur + cost[i-2]
                                                                                                                                                                                                                                  +        if last+cost[i-1] > cur+cost[i-2] {
                                                                                                                                                                                                                                  +            cur, last = last, cur+cost[i-2]
                                                                                                                                                                                                                                  +        } else {
                                                                                                                                                                                                                                  +            cur, last = last, last+cost[i-1]
                                                                                                                                                                                                                                  +        }
                                                                                                                                                                                                                                  +        // fmt.Printf("%-d | %-d | %-d\n", i, cur, last)
                                                                                                                                                                                                                                  +    }
                                                                                                                                                                                                                                  +    return last
                                                                                                                                                                                                                                  +}
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  +

                                                                                                                                                                                                                                  Benchmark

                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  goos: darwin
                                                                                                                                                                                                                                  +goarch: amd64
                                                                                                                                                                                                                                  +pkg: LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs
                                                                                                                                                                                                                                  +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz
                                                                                                                                                                                                                                  +BenchmarkMinCostClimbingStairs-4                36693742                30.17 ns/op           24 B/op          1 allocs/op
                                                                                                                                                                                                                                  +BenchmarkMinCostClimbingStairsOptimize-4        405489464                3.091 ns/op           0 B/op          0 allocs/op
                                                                                                                                                                                                                                  +PASS
                                                                                                                                                                                                                                  +ok      LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs   2.713s
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                                  results matching ""

                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                    No results matching ""

                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    + + + + + + +
                                                                                                                                                                                                                                    + + +
                                                                                                                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0746.Min-Cost-Climbing-Stairs/main.go b/Leetcode/0746.Min-Cost-Climbing-Stairs/main.go new file mode 100644 index 000000000..1edcb03d6 --- /dev/null +++ b/Leetcode/0746.Min-Cost-Climbing-Stairs/main.go @@ -0,0 +1,50 @@ +package mincostclimbingstairs + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +func MinCostClimbingStairs(cost []int) int { + dp := make([]int, len(cost)) + dp[0], dp[1] = cost[0], cost[1] + for i := 2; i < len(cost); i++ { + dp[i] = cost[i] + min(dp[i-1], dp[i-2]) + } + return min(dp[len(cost)-2], dp[len(cost)-1]) +} + +func min(a, b int) int { + if a > b { + return b + } + return a +} + +// ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) +// ๅ„ชๅŒ– +// ไฝฟ็”จไบ†ๅ…ฉๅ€‹่ฎŠๆ•ธcurๅ’Œlast๏ผŒ +// cur ่ฎŠๆ•ธๅญ˜ๅ„ฒๅพž็ฌฌ i-2 ๆญฅๅˆฐ้”็ฌฌ i ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒปใ€‚ +// last ่ฎŠๆ•ธๅญ˜ๅ„ฒๅพž็ฌฌ i-1 ๆญฅๅˆฐ้”็ฌฌ i ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒปใ€‚ +// ๆฏ”่ผƒๅ…ฉ็จฎ้ธๆ“‡็š„่Šฑ่ฒป๏ผš +// ๅพž็ฌฌ2้šŽ้–‹ๅง‹๏ผˆi := 2๏ผ‰๏ผŒไธ€็›ด่ฟญไปฃๅˆฐๆœ€ๅพŒไธ€้šŽ๏ผˆi < len(cost)+1๏ผ‰ใ€‚ +// ๅœจๆฏไธ€ๆญฅ้ฉŸไธญ๏ผš +// ๆฏ”่ผƒๅ…ฉ็จฎ้ธๆ“‡็š„่Šฑ่ฒป๏ผš +// +// ้ธๆ“‡ๅพžไธŠไธ€้šŽ่ทณๅˆฐ็•ถๅ‰้šŽ็š„่Šฑ่ฒป๏ผšlast + cost[i-1] +// ้ธๆ“‡ๅพžไธŠไธŠ้šŽ่ทณๅˆฐ็•ถๅ‰้šŽ็š„่Šฑ่ฒป๏ผšcur + cost[i-2] +// +// ้ธๆ“‡่Šฑ่ฒป่ผƒๅฐ็š„ๆ–นๆกˆ๏ผš +// +// ๅฆ‚ๆžœ last + cost[i-1] ๆ›ดๅฐ๏ผŒๅ‰‡ๅฐ‡ last ็š„ๅ€ผๆ›ดๆ–ฐ็‚บ cur + cost[i-2]๏ผŒไธฆๅฐ‡ cur ็š„ๅ€ผๆ›ดๆ–ฐ็‚บ last๏ผˆๅณไธŠไธ€ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒป๏ผ‰ใ€‚ +// ๅฆๅ‰‡๏ผŒๅฐ‡ last ็š„ๅ€ผๆ›ดๆ–ฐ็‚บ last + cost[i-1]๏ผŒไธฆๅฐ‡ cur ็š„ๅ€ผๆ›ดๆ–ฐ็‚บ last๏ผˆๅณไธŠไธ€ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒป๏ผ‰ใ€‚ +func MinCostClimbingStairsOptimize(cost []int) int { + var cur, last int + for i := 2; i < len(cost)+1; i++ { + // ้ธๆ“‡ๅพžไธŠไธ€้šŽ่ทณๅˆฐ็•ถๅ‰้šŽ็š„่Šฑ่ฒป๏ผšlast + cost[i-1] + // ้ธๆ“‡ๅพžไธŠไธŠ้šŽ่ทณๅˆฐ็•ถๅ‰้šŽ็š„่Šฑ่ฒป๏ผšcur + cost[i-2] + if last+cost[i-1] > cur+cost[i-2] { + cur, last = last, cur+cost[i-2] + } else { + cur, last = last, last+cost[i-1] + } + // fmt.Printf("%-d | %-d | %-d\n", i, cur, last) + } + return last +} diff --git a/Leetcode/0746.Min-Cost-Climbing-Stairs/main_test.go b/Leetcode/0746.Min-Cost-Climbing-Stairs/main_test.go new file mode 100644 index 000000000..64a64bcf7 --- /dev/null +++ b/Leetcode/0746.Min-Cost-Climbing-Stairs/main_test.go @@ -0,0 +1,61 @@ +package mincostclimbingstairs + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{10, 15, 20}, + 15, + }, + { + []int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}, + 6, + }, +} + +func TestMinCostClimbingStairs(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MinCostClimbingStairs(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestMinCostClimbingStairsOptimize(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := MinCostClimbingStairsOptimize(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkMinCostClimbingStairs(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinCostClimbingStairs(tests[0].arg1) + } +} + +func BenchmarkMinCostClimbingStairsOptimize(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + MinCostClimbingStairsOptimize(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs +cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz +BenchmarkMinCostClimbingStairs-4 36693742 30.17 ns/op 24 B/op 1 allocs/op +BenchmarkMinCostClimbingStairsOptimize-4 405489464 3.091 ns/op 0 B/op 0 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs 2.713s +*/ diff --git a/Leetcode/0752.Open-the-Lock/index.html b/Leetcode/0752.Open-the-Lock/index.html new file mode 100644 index 000000000..aac4ae550 --- /dev/null +++ b/Leetcode/0752.Open-the-Lock/index.html @@ -0,0 +1,4070 @@ + + + + + + + 0752.Open the Lock ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                    752. Open the Lock

                                                                                                                                                                                                                                    You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    The lock initially starts at '0000', a string representing the state of the 4 wheels.

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it.

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible.

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    Example 1:

                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
                                                                                                                                                                                                                                    +Output: 6
                                                                                                                                                                                                                                    +Explanation: 
                                                                                                                                                                                                                                    +A sequence of valid moves would be "0000" -> "1000" -> "1100" -> "1200" -> "1201" -> "1202" -> "0202".
                                                                                                                                                                                                                                    +Note that a sequence like "0000" -> "0001" -> "0002" -> "0102" -> "0202" would be invalid,
                                                                                                                                                                                                                                    +because the wheels of the lock become stuck after the display becomes the dead end "0102".
                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    Example 2:

                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    Input: deadends = ["8888"], target = "0009"
                                                                                                                                                                                                                                    +Output: 1
                                                                                                                                                                                                                                    +Explanation: We can turn the last wheel in reverse to move from "0000" -> "0009".
                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    Example 3:

                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888"
                                                                                                                                                                                                                                    +Output: -1
                                                                                                                                                                                                                                    +Explanation: We cannot reach the target without getting stuck.
                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    Constraints:

                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                    • 1 <= deadends.length <= 500
                                                                                                                                                                                                                                    • +
                                                                                                                                                                                                                                    • deadends[i].length == 4
                                                                                                                                                                                                                                    • +
                                                                                                                                                                                                                                    • target.length == 4
                                                                                                                                                                                                                                    • +
                                                                                                                                                                                                                                    • target will not be in the list deadends.
                                                                                                                                                                                                                                    • +
                                                                                                                                                                                                                                    • target and deadends[i] consist of digits only.
                                                                                                                                                                                                                                    • +
                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    題目大意

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    有一個四個圓形播盤的轉盤鎖, 每個播盤有0~9共10個數字, 每個播盤上下旋轉可以把 0變成9 或 9變成0. 每次只能旋轉一個播盤 +初始直接為0.且有一組 deadends 數組. 不能接數字轉到其中任一組. 如果無法得到 target 回傳 -1

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    解題思路

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    從 0000開始轉, 轉一次可窮舉出 "1000", "9000", "0100", "0900", "0010", "0090", "0001", "0009". 8 總可能, +再以這八種密碼為基礎, 對每總密碼再轉一下, 窮舉出每個可能 +可以抽象成一副圖, 每個節點有8個相鄰的節點, 讓你求出最短距離

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    方法二: 還可以用雙向BFS, 從起點跟終點開始擴散, 當兩邊有交集時停止

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    方法三: 雙向 BFS 優化, 在 while 開始時做一個判斷. 讓每次都選擇較小的集合進行擴散, +那麼佔用的空間增長速度就會慢一些, 盡可能以最小的空間代價產生 curDepth 和 nextDepth 的交集 +無論單向的 BFS 或是 雙向BFS, 優化過的BFS 空間複雜度都是一樣的

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    來源

                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                    解答

                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                    https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0752.Open-the-Lock/main.go

                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    package openthelock
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +// 方法ㄧ: 單向BFS
                                                                                                                                                                                                                                    +func OpenLock(deadends []string, target string) int {
                                                                                                                                                                                                                                    +    if target == "0000" {
                                                                                                                                                                                                                                    +        return 0
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +    targetNum := strToInt(target)
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    // 紀錄已窮舉過的密碼, 防止走回頭路
                                                                                                                                                                                                                                    +    visited := make([]bool, 10000)
                                                                                                                                                                                                                                    +    visited[0] = true
                                                                                                                                                                                                                                    +    for _, deadend := range deadends {
                                                                                                                                                                                                                                    +        num := strToInt(deadend)
                                                                                                                                                                                                                                    +        if num == 0 {
                                                                                                                                                                                                                                    +            return -1
                                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                                    +        visited[num] = true
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    depth, curDepth, nextDepth := 0, []int16{0}, make([]int16, 0)
                                                                                                                                                                                                                                    +    var nextNum int16
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    for len(curDepth) > 0 {
                                                                                                                                                                                                                                    +        nextDepth = nextDepth[0:0]
                                                                                                                                                                                                                                    +        // 當前Queue中所有的節點向外擴散
                                                                                                                                                                                                                                    +        for _, curNum := range curDepth {
                                                                                                                                                                                                                                    +            // 遍歷八種組合
                                                                                                                                                                                                                                    +            for incrementer := int16(1000); incrementer > 0; incrementer /= 10 {
                                                                                                                                                                                                                                    +                nextNum = PlusOne(curNum, incrementer)
                                                                                                                                                                                                                                    +                if nextNum == targetNum {
                                                                                                                                                                                                                                    +                    return depth + 1
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +                if !visited[nextNum] {
                                                                                                                                                                                                                                    +                    visited[nextNum] = true
                                                                                                                                                                                                                                    +                    nextDepth = append(nextDepth, nextNum)
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +                nextNum = MinusOne(curNum, incrementer)
                                                                                                                                                                                                                                    +                if nextNum == targetNum {
                                                                                                                                                                                                                                    +                    return depth + 1
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +                if !visited[nextNum] {
                                                                                                                                                                                                                                    +                    visited[nextNum] = true
                                                                                                                                                                                                                                    +                    nextDepth = append(nextDepth, nextNum)
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                                    +        curDepth, nextDepth = nextDepth, curDepth
                                                                                                                                                                                                                                    +        // 增加步數
                                                                                                                                                                                                                                    +        depth++
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    return -1
                                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +/* Note: Golang set
                                                                                                                                                                                                                                    +type void struct{}
                                                                                                                                                                                                                                    +var member void
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +set := make(map[string]void) // New empty set
                                                                                                                                                                                                                                    +set["Foo"] = member          // Add
                                                                                                                                                                                                                                    +for k := range set {         // Loop
                                                                                                                                                                                                                                    +    fmt.Println(k)
                                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                                    +delete(set, "Foo")      // Delete
                                                                                                                                                                                                                                    +size := len(set)        // Size
                                                                                                                                                                                                                                    +_, exists := set["Foo"] // Membership
                                                                                                                                                                                                                                    +*/
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +// 方法二: 雙向BFS. 不在使用 Queue而是用 hashset, 快速判斷兩者是否交集
                                                                                                                                                                                                                                    +// 從起點跟終點開始擴散, 當兩邊有交集時停止
                                                                                                                                                                                                                                    +func OpenLockBiDirection(deadends []string, target string) int {
                                                                                                                                                                                                                                    +    if target == "0000" {
                                                                                                                                                                                                                                    +        return 0
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +    targetNum := strToInt(target)
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    // 紀錄已窮舉過的密碼, 防止走回頭路
                                                                                                                                                                                                                                    +    visited := make([]bool, 10000)
                                                                                                                                                                                                                                    +    for _, deadend := range deadends {
                                                                                                                                                                                                                                    +        num := strToInt(deadend)
                                                                                                                                                                                                                                    +        if num == 0 {
                                                                                                                                                                                                                                    +            return -1
                                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                                    +        visited[num] = true
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    depth := 0
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    // 起點跟終點初始化
                                                                                                                                                                                                                                    +    curDepth := make(map[int16]struct{})
                                                                                                                                                                                                                                    +    nextDepth := make(map[int16]struct{})
                                                                                                                                                                                                                                    +    curDepth[0] = struct{}{}
                                                                                                                                                                                                                                    +    nextDepth[targetNum] = struct{}{}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    var nextNum int16
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    for len(curDepth) != 0 && len(nextDepth) != 0 {
                                                                                                                                                                                                                                    +        // 儲存 curDepth 的擴散結果
                                                                                                                                                                                                                                    +        tmp := make(map[int16]struct{})
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +        // curDepth的節點向外擴散
                                                                                                                                                                                                                                    +        for curNum := range curDepth {
                                                                                                                                                                                                                                    +            // 判斷是否達到終點
                                                                                                                                                                                                                                    +            if visited[curNum] {
                                                                                                                                                                                                                                    +                continue
                                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                                    +            _, exists := nextDepth[curNum]
                                                                                                                                                                                                                                    +            if exists {
                                                                                                                                                                                                                                    +                return depth
                                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                                    +            visited[curNum] = true
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +            // 遍歷八種組合
                                                                                                                                                                                                                                    +            for incrementer := int16(1000); incrementer > 0; incrementer /= 10 {
                                                                                                                                                                                                                                    +                nextNum = PlusOne(curNum, incrementer)
                                                                                                                                                                                                                                    +                if !visited[nextNum] {
                                                                                                                                                                                                                                    +                    tmp[nextNum] = struct{}{}
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +                nextNum = MinusOne(curNum, incrementer)
                                                                                                                                                                                                                                    +                if !visited[nextNum] {
                                                                                                                                                                                                                                    +                    tmp[nextNum] = struct{}{}
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +        // 小技巧, 這裏交換 curDepth, nextDepth .
                                                                                                                                                                                                                                    +        // 下一輪 whihe會擴散 nextDepth.
                                                                                                                                                                                                                                    +        // 所以只要默認擴散curDepth, 就相當於輪流擴散curDepth, nextDepth
                                                                                                                                                                                                                                    +        curDepth, nextDepth = nextDepth, tmp
                                                                                                                                                                                                                                    +        // 增加步數
                                                                                                                                                                                                                                    +        depth++
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    return -1
                                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +// 方法三 : 雙向 BFS 優化, 在 while 開始時做一個判斷. 讓每次都選擇較小的集合進行擴散,
                                                                                                                                                                                                                                    +// 那麼佔用的空間增長速度就會慢一些, 盡可能以最小的空間代價產生 curDepth 和 nextDepth 的交集
                                                                                                                                                                                                                                    +// 無論單向的 BFS 或是 雙向BFS, 優化過的BFS 空間複雜度都是一樣的
                                                                                                                                                                                                                                    +func OpenLockBiDirectionOptimization(deadends []string, target string) int {
                                                                                                                                                                                                                                    +    if target == "0000" {
                                                                                                                                                                                                                                    +        return 0
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +    targetNum := strToInt(target)
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    // 紀錄已窮舉過的密碼, 防止走回頭路
                                                                                                                                                                                                                                    +    visited := make([]bool, 10000)
                                                                                                                                                                                                                                    +    for _, deadend := range deadends {
                                                                                                                                                                                                                                    +        num := strToInt(deadend)
                                                                                                                                                                                                                                    +        if num == 0 {
                                                                                                                                                                                                                                    +            return -1
                                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                                    +        visited[num] = true
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    depth := 0
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    // 起點跟終點初始化
                                                                                                                                                                                                                                    +    curDepth := make(map[int16]struct{})
                                                                                                                                                                                                                                    +    nextDepth := make(map[int16]struct{})
                                                                                                                                                                                                                                    +    curDepth[0] = struct{}{}
                                                                                                                                                                                                                                    +    nextDepth[targetNum] = struct{}{}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    var nextNum int16
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    for len(curDepth) != 0 && len(nextDepth) != 0 {
                                                                                                                                                                                                                                    +        if len(curDepth) > len(nextDepth) {
                                                                                                                                                                                                                                    +            curDepth, nextDepth = nextDepth, curDepth
                                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                                    +        // 儲存 curDepth 的擴散結果
                                                                                                                                                                                                                                    +        tmp := make(map[int16]struct{})
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +        // curDepth的節點向外擴散
                                                                                                                                                                                                                                    +        for curNum := range curDepth {
                                                                                                                                                                                                                                    +            // 判斷是否達到終點
                                                                                                                                                                                                                                    +            if visited[curNum] {
                                                                                                                                                                                                                                    +                continue
                                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                                    +            _, exists := nextDepth[curNum]
                                                                                                                                                                                                                                    +            if exists {
                                                                                                                                                                                                                                    +                return depth
                                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                                    +            visited[curNum] = true
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +            // 遍歷八種組合
                                                                                                                                                                                                                                    +            for incrementer := int16(1000); incrementer > 0; incrementer /= 10 {
                                                                                                                                                                                                                                    +                nextNum = PlusOne(curNum, incrementer)
                                                                                                                                                                                                                                    +                if !visited[nextNum] {
                                                                                                                                                                                                                                    +                    tmp[nextNum] = struct{}{}
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +                nextNum = MinusOne(curNum, incrementer)
                                                                                                                                                                                                                                    +                if !visited[nextNum] {
                                                                                                                                                                                                                                    +                    tmp[nextNum] = struct{}{}
                                                                                                                                                                                                                                    +                }
                                                                                                                                                                                                                                    +            }
                                                                                                                                                                                                                                    +        }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +        // 小技巧, 這裏交換 curDepth, nextDepth .
                                                                                                                                                                                                                                    +        // 下一輪 whihe會擴散 nextDepth.
                                                                                                                                                                                                                                    +        // 所以只要默認擴散curDepth, 就相當於輪流擴散curDepth, nextDepth
                                                                                                                                                                                                                                    +        curDepth, nextDepth = nextDepth, tmp
                                                                                                                                                                                                                                    +        // 增加步數
                                                                                                                                                                                                                                    +        depth++
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +    return -1
                                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +func PlusOne(curNum int16, incrementer int16) (nextNum int16) {
                                                                                                                                                                                                                                    +    digit := (curNum / incrementer) % 10
                                                                                                                                                                                                                                    +    if digit == 9 {
                                                                                                                                                                                                                                    +        nextNum = curNum - 9*incrementer
                                                                                                                                                                                                                                    +    } else {
                                                                                                                                                                                                                                    +        nextNum = curNum + incrementer
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +    return nextNum
                                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +func MinusOne(curNum int16, incrementer int16) (nextNum int16) {
                                                                                                                                                                                                                                    +    digit := (curNum / incrementer) % 10
                                                                                                                                                                                                                                    +    if digit == 0 {
                                                                                                                                                                                                                                    +        nextNum = curNum + 9*incrementer
                                                                                                                                                                                                                                    +    } else {
                                                                                                                                                                                                                                    +        nextNum = curNum - incrementer
                                                                                                                                                                                                                                    +    }
                                                                                                                                                                                                                                    +    return nextNum
                                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +func strToInt(str string) int16 {
                                                                                                                                                                                                                                    +    return int16(str[0]-'0')*1000 + int16(str[1]-'0')*100 + int16(str[2]-'0')*10 + int16(str[3]-'0')
                                                                                                                                                                                                                                    +}
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    tags: Medium Leetcode BFS
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                    results matching ""

                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                                      No results matching ""

                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      + + + + + + +
                                                                                                                                                                                                                                      + + +
                                                                                                                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0752.Open-the-Lock/main.go b/Leetcode/0752.Open-the-Lock/main.go new file mode 100644 index 000000000..12847b60b --- /dev/null +++ b/Leetcode/0752.Open-the-Lock/main.go @@ -0,0 +1,235 @@ +package openthelock + +// ๆ–นๆณ•ใ„ง: ๅ–ฎๅ‘BFS +func OpenLock(deadends []string, target string) int { + if target == "0000" { + return 0 + } + targetNum := strToInt(target) + + // ็ด€้Œ„ๅทฒ็ชฎ่ˆ‰้Ž็š„ๅฏ†็ขผ, ้˜ฒๆญข่ตฐๅ›ž้ ญ่ทฏ + visited := make([]bool, 10000) + visited[0] = true + for _, deadend := range deadends { + num := strToInt(deadend) + if num == 0 { + return -1 + } + visited[num] = true + } + + depth, curDepth, nextDepth := 0, []int16{0}, make([]int16, 0) + var nextNum int16 + + for len(curDepth) > 0 { + nextDepth = nextDepth[0:0] + // ็•ถๅ‰Queueไธญๆ‰€ๆœ‰็š„็ฏ€้ปžๅ‘ๅค–ๆ“ดๆ•ฃ + for _, curNum := range curDepth { + // ้ๆญทๅ…ซ็จฎ็ต„ๅˆ + for incrementer := int16(1000); incrementer > 0; incrementer /= 10 { + nextNum = PlusOne(curNum, incrementer) + if nextNum == targetNum { + return depth + 1 + } + if !visited[nextNum] { + visited[nextNum] = true + nextDepth = append(nextDepth, nextNum) + } + + nextNum = MinusOne(curNum, incrementer) + if nextNum == targetNum { + return depth + 1 + } + if !visited[nextNum] { + visited[nextNum] = true + nextDepth = append(nextDepth, nextNum) + } + } + } + curDepth, nextDepth = nextDepth, curDepth + // ๅขžๅŠ ๆญฅๆ•ธ + depth++ + } + + return -1 +} + +/* Note: Golang set +type void struct{} +var member void + +set := make(map[string]void) // New empty set +set["Foo"] = member // Add +for k := range set { // Loop + fmt.Println(k) +} +delete(set, "Foo") // Delete +size := len(set) // Size +_, exists := set["Foo"] // Membership +*/ + +// ๆ–นๆณ•ไบŒ: ้›™ๅ‘BFS. ไธๅœจไฝฟ็”จ Queue่€Œๆ˜ฏ็”จ hashset, ๅฟซ้€Ÿๅˆคๆ–ทๅ…ฉ่€…ๆ˜ฏๅฆไบค้›† +// ๅพž่ตท้ปž่ทŸ็ต‚้ปž้–‹ๅง‹ๆ“ดๆ•ฃ, ็•ถๅ…ฉ้‚Šๆœ‰ไบค้›†ๆ™‚ๅœๆญข +func OpenLockBiDirection(deadends []string, target string) int { + if target == "0000" { + return 0 + } + targetNum := strToInt(target) + + // ็ด€้Œ„ๅทฒ็ชฎ่ˆ‰้Ž็š„ๅฏ†็ขผ, ้˜ฒๆญข่ตฐๅ›ž้ ญ่ทฏ + visited := make([]bool, 10000) + for _, deadend := range deadends { + num := strToInt(deadend) + if num == 0 { + return -1 + } + visited[num] = true + } + + depth := 0 + + // ่ตท้ปž่ทŸ็ต‚้ปžๅˆๅง‹ๅŒ– + curDepth := make(map[int16]struct{}) + nextDepth := make(map[int16]struct{}) + curDepth[0] = struct{}{} + nextDepth[targetNum] = struct{}{} + + var nextNum int16 + + for len(curDepth) != 0 && len(nextDepth) != 0 { + // ๅ„ฒๅญ˜ curDepth ็š„ๆ“ดๆ•ฃ็ตๆžœ + tmp := make(map[int16]struct{}) + + // curDepth็š„็ฏ€้ปžๅ‘ๅค–ๆ“ดๆ•ฃ + for curNum := range curDepth { + // ๅˆคๆ–ทๆ˜ฏๅฆ้”ๅˆฐ็ต‚้ปž + if visited[curNum] { + continue + } + _, exists := nextDepth[curNum] + if exists { + return depth + } + visited[curNum] = true + + // ้ๆญทๅ…ซ็จฎ็ต„ๅˆ + for incrementer := int16(1000); incrementer > 0; incrementer /= 10 { + nextNum = PlusOne(curNum, incrementer) + if !visited[nextNum] { + tmp[nextNum] = struct{}{} + } + + nextNum = MinusOne(curNum, incrementer) + if !visited[nextNum] { + tmp[nextNum] = struct{}{} + } + } + } + + // ๅฐๆŠ€ๅทง, ้€™่ฃไบคๆ› curDepth, nextDepth . + // ไธ‹ไธ€่ผช whiheๆœƒๆ“ดๆ•ฃ nextDepth. + // ๆ‰€ไปฅๅช่ฆ้ป˜่ชๆ“ดๆ•ฃcurDepth, ๅฐฑ็›ธ็•ถๆ–ผ่ผชๆตๆ“ดๆ•ฃcurDepth, nextDepth + curDepth, nextDepth = nextDepth, tmp + // ๅขžๅŠ ๆญฅๆ•ธ + depth++ + } + + return -1 +} + +// ๆ–นๆณ•ไธ‰ : ้›™ๅ‘ BFS ๅ„ชๅŒ–, ๅœจ while ้–‹ๅง‹ๆ™‚ๅšไธ€ๅ€‹ๅˆคๆ–ท. ่ฎ“ๆฏๆฌก้ƒฝ้ธๆ“‡่ผƒๅฐ็š„้›†ๅˆ้€ฒ่กŒๆ“ดๆ•ฃ, +// ้‚ฃ้บผไฝ”็”จ็š„็ฉบ้–“ๅขž้•ท้€Ÿๅบฆๅฐฑๆœƒๆ…ขไธ€ไบ›, ็›กๅฏ่ƒฝไปฅๆœ€ๅฐ็š„็ฉบ้–“ไปฃๅƒน็”ข็”Ÿ curDepth ๅ’Œ nextDepth ็š„ไบค้›† +// ็„ก่ซ–ๅ–ฎๅ‘็š„ BFS ๆˆ–ๆ˜ฏ ้›™ๅ‘BFS, ๅ„ชๅŒ–้Ž็š„BFS ็ฉบ้–“่ค‡้›œๅบฆ้ƒฝๆ˜ฏไธ€ๆจฃ็š„ +func OpenLockBiDirectionOptimization(deadends []string, target string) int { + if target == "0000" { + return 0 + } + targetNum := strToInt(target) + + // ็ด€้Œ„ๅทฒ็ชฎ่ˆ‰้Ž็š„ๅฏ†็ขผ, ้˜ฒๆญข่ตฐๅ›ž้ ญ่ทฏ + visited := make([]bool, 10000) + for _, deadend := range deadends { + num := strToInt(deadend) + if num == 0 { + return -1 + } + visited[num] = true + } + + depth := 0 + + // ่ตท้ปž่ทŸ็ต‚้ปžๅˆๅง‹ๅŒ– + curDepth := make(map[int16]struct{}) + nextDepth := make(map[int16]struct{}) + curDepth[0] = struct{}{} + nextDepth[targetNum] = struct{}{} + + var nextNum int16 + + for len(curDepth) != 0 && len(nextDepth) != 0 { + if len(curDepth) > len(nextDepth) { + curDepth, nextDepth = nextDepth, curDepth + } + // ๅ„ฒๅญ˜ curDepth ็š„ๆ“ดๆ•ฃ็ตๆžœ + tmp := make(map[int16]struct{}) + + // curDepth็š„็ฏ€้ปžๅ‘ๅค–ๆ“ดๆ•ฃ + for curNum := range curDepth { + // ๅˆคๆ–ทๆ˜ฏๅฆ้”ๅˆฐ็ต‚้ปž + if visited[curNum] { + continue + } + _, exists := nextDepth[curNum] + if exists { + return depth + } + visited[curNum] = true + + // ้ๆญทๅ…ซ็จฎ็ต„ๅˆ + for incrementer := int16(1000); incrementer > 0; incrementer /= 10 { + nextNum = PlusOne(curNum, incrementer) + if !visited[nextNum] { + tmp[nextNum] = struct{}{} + } + + nextNum = MinusOne(curNum, incrementer) + if !visited[nextNum] { + tmp[nextNum] = struct{}{} + } + } + } + + // ๅฐๆŠ€ๅทง, ้€™่ฃไบคๆ› curDepth, nextDepth . + // ไธ‹ไธ€่ผช whiheๆœƒๆ“ดๆ•ฃ nextDepth. + // ๆ‰€ไปฅๅช่ฆ้ป˜่ชๆ“ดๆ•ฃcurDepth, ๅฐฑ็›ธ็•ถๆ–ผ่ผชๆตๆ“ดๆ•ฃcurDepth, nextDepth + curDepth, nextDepth = nextDepth, tmp + // ๅขžๅŠ ๆญฅๆ•ธ + depth++ + } + + return -1 +} + +func PlusOne(curNum int16, incrementer int16) (nextNum int16) { + digit := (curNum / incrementer) % 10 + if digit == 9 { + nextNum = curNum - 9*incrementer + } else { + nextNum = curNum + incrementer + } + return nextNum +} + +func MinusOne(curNum int16, incrementer int16) (nextNum int16) { + digit := (curNum / incrementer) % 10 + if digit == 0 { + nextNum = curNum + 9*incrementer + } else { + nextNum = curNum - incrementer + } + return nextNum +} + +func strToInt(str string) int16 { + return int16(str[0]-'0')*1000 + int16(str[1]-'0')*100 + int16(str[2]-'0')*10 + int16(str[3]-'0') +} diff --git a/Leetcode/0752.Open-the-Lock/main_test.go b/Leetcode/0752.Open-the-Lock/main_test.go new file mode 100644 index 000000000..f51cb19d6 --- /dev/null +++ b/Leetcode/0752.Open-the-Lock/main_test.go @@ -0,0 +1,85 @@ +package openthelock + +import ( + "testing" +) + +var tests = []struct { + arg1 []string + arg2 string + want int +}{ + { + []string{"0201", "0101", "0102", "1212", "2002"}, + "0202", + 6, + }, + { + []string{"8888"}, + "0009", + 1, + }, + { + []string{"8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888"}, + "8888", + -1, + }, +} + +func TestOpenLock(t *testing.T) { + for _, tt := range tests { + if got := OpenLock(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestOpenLockBiDirection(t *testing.T) { + for _, tt := range tests { + if got := OpenLockBiDirection(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func TestOpenLockBiDirection๏ผฏptimization(t *testing.T) { + for _, tt := range tests { + if got := OpenLockBiDirectionOptimization(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v \n want = %v \n", got, tt.want) + } + } +} + +func BenchmarkOpenLock(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + OpenLock(tests[i%3].arg1, tests[i%3].arg2) + } +} + +func BenchmarkOpenLockBiDirection(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + OpenLockBiDirection(tests[i%3].arg1, tests[i%3].arg2) + } +} + +func BenchmarkOpenLockBiDirectionOptimization(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + OpenLockBiDirectionOptimization(tests[i%3].arg1, tests[i%3].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0752.Open-the-Lock -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/0752.Open-the-Lock +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkOpenLock-8 12866 92523 ns/op 5543 B/op 12 allocs/op +BenchmarkOpenLockBiDirection-8 79819 14357 ns/op 1722 B/op 28 allocs/op +BenchmarkOpenLockBiDirectionOptimization-8 85179 14486 ns/op 1721 B/op 28 allocs/op +PASS +ok LeetcodeGolang/Leetcode/0752.Open-the-Lock 4.820s +*/ diff --git a/Leetcode/0876.Middle-of-the-Linked-List/index.html b/Leetcode/0876.Middle-of-the-Linked-List/index.html new file mode 100644 index 000000000..086fd6b4a --- /dev/null +++ b/Leetcode/0876.Middle-of-the-Linked-List/index.html @@ -0,0 +1,3858 @@ + + + + + + + 0876.Middle of the Linked List ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                                      876. Middle of the Linked List

                                                                                                                                                                                                                                      題目

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      Given the head of a singly linked list, return the middle node of the linked list.

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      If there are two middle nodes, return the second middle node.

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      Example 1:

                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      Input: head = [1,2,3,4,5]
                                                                                                                                                                                                                                      +Output: [3,4,5]
                                                                                                                                                                                                                                      +Explanation: The middle node of the list is node 3.
                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      Example 2:

                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      Input: head = [1,2,3,4,5,6]
                                                                                                                                                                                                                                      +Output: [4,5,6]
                                                                                                                                                                                                                                      +Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      Constraints:

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      The number of nodes in the list is in the range [1, 100]. +1 <= Node.val <= 100

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      題目大意

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      尋找無環的 linked list 的中間節點

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      解題思路

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      使用 two pointer. 讓快指針往前兩步. 慢指針往前一步. 當快指針到達盡頭時, 慢指針就位於linked list的中間位置. +當linked list的長度為奇數時, slow剛好停在中點位置; +如果長度為偶數, slow停在中間偏右

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      來源

                                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                                      解答

                                                                                                                                                                                                                                      +

                                                                                                                                                                                                                                      https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0876.Middle-of-the-Linked-List/main.go

                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      package middleofthelinkedlist
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +/**
                                                                                                                                                                                                                                      + * Definition for singly-linked list.
                                                                                                                                                                                                                                      + * type ListNode struct {
                                                                                                                                                                                                                                      + *     Val int
                                                                                                                                                                                                                                      + *     Next *ListNode
                                                                                                                                                                                                                                      + * }
                                                                                                                                                                                                                                      + */
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +type ListNode struct {
                                                                                                                                                                                                                                      +    Val  int
                                                                                                                                                                                                                                      +    Next *ListNode
                                                                                                                                                                                                                                      +}
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +func MiddleNode(head *ListNode) *ListNode {
                                                                                                                                                                                                                                      +    if head == nil || head.Next == nil {
                                                                                                                                                                                                                                      +        return head
                                                                                                                                                                                                                                      +    }
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +    fast, slow := head, head
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +    for fast.Next != nil && fast.Next.Next != nil {
                                                                                                                                                                                                                                      +        fast = fast.Next.Next
                                                                                                                                                                                                                                      +        slow = slow.Next
                                                                                                                                                                                                                                      +    }
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +    // 算出長度
                                                                                                                                                                                                                                      +    curr := head
                                                                                                                                                                                                                                      +    length := 0
                                                                                                                                                                                                                                      +    for curr != nil {
                                                                                                                                                                                                                                      +        length++
                                                                                                                                                                                                                                      +        curr = curr.Next
                                                                                                                                                                                                                                      +    }
                                                                                                                                                                                                                                      +    if length%2 == 0 {
                                                                                                                                                                                                                                      +        // 偶數
                                                                                                                                                                                                                                      +        return slow.Next
                                                                                                                                                                                                                                      +    } else {
                                                                                                                                                                                                                                      +        // 奇數
                                                                                                                                                                                                                                      +        return slow
                                                                                                                                                                                                                                      +    }
                                                                                                                                                                                                                                      +}
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      tags: Medium Leetcode two pointers
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                                      results matching ""

                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                                        No results matching ""

                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        + + + + + + +
                                                                                                                                                                                                                                        + + +
                                                                                                                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/0876.Middle-of-the-Linked-List/main.go b/Leetcode/0876.Middle-of-the-Linked-List/main.go new file mode 100644 index 000000000..a808e69f4 --- /dev/null +++ b/Leetcode/0876.Middle-of-the-Linked-List/main.go @@ -0,0 +1,42 @@ +package middleofthelinkedlist + +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + +type ListNode struct { + Val int + Next *ListNode +} + +func MiddleNode(head *ListNode) *ListNode { + if head == nil || head.Next == nil { + return head + } + + fast, slow := head, head + + for fast.Next != nil && fast.Next.Next != nil { + fast = fast.Next.Next + slow = slow.Next + } + + // ็ฎ—ๅ‡บ้•ทๅบฆ + curr := head + length := 0 + for curr != nil { + length++ + curr = curr.Next + } + if length%2 == 0 { + // ๅถๆ•ธ + return slow.Next + } else { + // ๅฅ‡ๆ•ธ + return slow + } +} diff --git a/Leetcode/0876.Middle-of-the-Linked-List/main_test.go b/Leetcode/0876.Middle-of-the-Linked-List/main_test.go new file mode 100644 index 000000000..484aaaff8 --- /dev/null +++ b/Leetcode/0876.Middle-of-the-Linked-List/main_test.go @@ -0,0 +1,38 @@ +package middleofthelinkedlist + +import ( + "reflect" + "testing" +) + +func TestMiddleNode(t *testing.T) { + a := &ListNode{1, nil} + b := &ListNode{2, nil} + c := &ListNode{3, nil} + d := &ListNode{4, nil} + e := &ListNode{5, nil} + f := &ListNode{6, nil} + + a.Next = b + b.Next = c + c.Next = d + d.Next = e + e.Next = f + f.Next = nil + + tests := []struct { + arg1 *ListNode + want *ListNode + }{ + { + arg1: a, + want: d, + }, + } + + for _, tt := range tests { + if got := MiddleNode(tt.arg1); !reflect.DeepEqual(got, tt.want) { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} diff --git a/Leetcode/1046.Last-Stone-Weight/index.html b/Leetcode/1046.Last-Stone-Weight/index.html new file mode 100644 index 000000000..92c57e946 --- /dev/null +++ b/Leetcode/1046.Last-Stone-Weight/index.html @@ -0,0 +1,3917 @@ + + + + + + + 1046. Last Stone Weight ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        + + + + + + + + +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                                        1046. Last Stone Weight

                                                                                                                                                                                                                                        題目

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        You are given an array of integers stones where stones[i] is the weight of the ith stone.

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result of this smash is:

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        If x == y, both stones are destroyed, and +If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. +At the end of the game, there is at most one stone left.

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        Return the weight of the last remaining stone. If there are no stones left, return 0.

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        Example 1:

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        Input: stones = [2,7,4,1,8,1] +Output: 1 +Explanation: +We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, +we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, +we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, +we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. +Example 2:

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        Input: stones = [1] +Output: 1

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        Constraints:

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        1 <= stones.length <= 30 +1 <= stones[i] <= 1000

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        題目大意

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        有一個集合 stones,每個 stone 的重量由正整數表示。 +每次可以選擇兩個不同的石頭,將它們一起粉碎,然後得到一個新的石頭,其重量為兩者之差。 +你需要重複這個過程,直到集合中只剩下一個石頭,或者集合中沒有石頭為止。 +在這個過程中,找到可能的最後一顆石頭的重量。如果集合中沒有石頭,則返回 0。

                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        Input: stones = [2,7,4,1,8,1]
                                                                                                                                                                                                                                        +Output: 1
                                                                                                                                                                                                                                        +Explanation:
                                                                                                                                                                                                                                        +步驟1:選擇石頭 7 和 8,得到新石頭 [2,4,1,1,1]。
                                                                                                                                                                                                                                        +步驟2:選擇石頭 2 和 4,得到新石頭 [2,1,1,1]。
                                                                                                                                                                                                                                        +步驟3:選擇石頭 2 和 1,得到新石頭 [1,1,1]。
                                                                                                                                                                                                                                        +步驟4:選擇石頭 1 和 1,得到新石頭 [0,1]。
                                                                                                                                                                                                                                        +步驟5:選擇石頭 1 和 0,得到新石頭 [1]。
                                                                                                                                                                                                                                        +最後剩下的石頭的重量為 1。
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        解題思路

                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                        1. 將 stones 陣列轉換為最大堆(max heap),可以使用優先佇列實現。
                                                                                                                                                                                                                                        2. +
                                                                                                                                                                                                                                        3. 進行迴圈,每次從最大堆中取出兩個最大的石頭。
                                                                                                                                                                                                                                        4. +
                                                                                                                                                                                                                                        5. 如果兩個石頭不相等,將它們的差值插入最大堆。
                                                                                                                                                                                                                                        6. +
                                                                                                                                                                                                                                        7. 重複上述步驟,直到最大堆中只剩下一個石頭或沒有石頭為止。
                                                                                                                                                                                                                                        8. +
                                                                                                                                                                                                                                        9. 如果最大堆中有石頭,返回該石頭的重量,否則返回 0。 +這樣的做法確保每次都選擇最大的兩個石頭進行粉碎,最終留下的石頭重量就是可能的最後一個石頭的重量。
                                                                                                                                                                                                                                        10. +
                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        參考 0215 Kth Largest Element in an Array

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        Big O

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        時間複雜 : O(nlogn) +空間複雜 : O(n)

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        n 是石頭數量. 每次從隊列中取出元素需要話O(logn) 的時間, 最多共需要需要粉碎 n−1 次石頭

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        來源

                                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                                        解答

                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/1046.Last-Stone-Weight/main.go

                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        package laststoneweight
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +import (
                                                                                                                                                                                                                                        +    "container/heap"
                                                                                                                                                                                                                                        +    "fmt"
                                                                                                                                                                                                                                        +    "sort"
                                                                                                                                                                                                                                        +)
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +/*
                                                                                                                                                                                                                                        +// IntSlice attaches the methods of Interface to []int, sorting in increasing order.
                                                                                                                                                                                                                                        +type IntSlice []int
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +func (x IntSlice) Len() int           { return len(x) }
                                                                                                                                                                                                                                        +func (x IntSlice) Less(i, j int) bool { return x[i] < x[j] }
                                                                                                                                                                                                                                        +func (x IntSlice) Swap(i, j int)      { x[i], x[j] = x[j], x[i] }
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +// Sort is a convenience method: x.Sort() calls Sort(x).
                                                                                                                                                                                                                                        +func (x IntSlice) Sort() { Sort(x) }
                                                                                                                                                                                                                                        +*/
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +type hp struct {
                                                                                                                                                                                                                                        +    sort.IntSlice
                                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +func (h hp) Less(i, j int) bool {
                                                                                                                                                                                                                                        +    // 大到小排序
                                                                                                                                                                                                                                        +    return h.IntSlice[i] > h.IntSlice[j]
                                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +func (h *hp) Push(v interface{}) {
                                                                                                                                                                                                                                        +    h.IntSlice = append(h.IntSlice, v.(int))
                                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +func (h *hp) Pop() interface{} {
                                                                                                                                                                                                                                        +    old := h.IntSlice
                                                                                                                                                                                                                                        +    v := old[len(old)-1]
                                                                                                                                                                                                                                        +    h.IntSlice = old[:len(old)-1]
                                                                                                                                                                                                                                        +    return v
                                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +func (h *hp) PushInt(v int) {
                                                                                                                                                                                                                                        +    heap.Push(h, v)
                                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +func (h *hp) PopInt() int {
                                                                                                                                                                                                                                        +    return heap.Pop(h).(int)
                                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +// 時間複雜 O(nlogn), 空間複雜 O(n)
                                                                                                                                                                                                                                        +// n 是石頭數量. 每次從隊列中取出元素需要話O(logn) 的時間, 最多共需要需要粉碎 n−1 次石頭
                                                                                                                                                                                                                                        +func LastStoneWeight(stones []int) int {
                                                                                                                                                                                                                                        +    q := &hp{stones}
                                                                                                                                                                                                                                        +    heap.Init(q)
                                                                                                                                                                                                                                        +    fmt.Println(q)
                                                                                                                                                                                                                                        +    for q.Len() > 1 {
                                                                                                                                                                                                                                        +        fmt.Println(q)
                                                                                                                                                                                                                                        +        x, y := q.PopInt(), q.PopInt()
                                                                                                                                                                                                                                        +        fmt.Printf("%d,%d\n", x, y)
                                                                                                                                                                                                                                        +        if x > y {
                                                                                                                                                                                                                                        +            q.PushInt(x - y)
                                                                                                                                                                                                                                        +        }
                                                                                                                                                                                                                                        +    }
                                                                                                                                                                                                                                        +    if q.Len() > 0 {
                                                                                                                                                                                                                                        +        return q.IntSlice[0]
                                                                                                                                                                                                                                        +    }
                                                                                                                                                                                                                                        +    return 0
                                                                                                                                                                                                                                        +}
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +

                                                                                                                                                                                                                                        Benchmark

                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                                        results matching ""

                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                                          No results matching ""

                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          + + + + + + +
                                                                                                                                                                                                                                          + + +
                                                                                                                                                                                                                                          + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/1046.Last-Stone-Weight/main.go b/Leetcode/1046.Last-Stone-Weight/main.go new file mode 100644 index 000000000..6e6743b3a --- /dev/null +++ b/Leetcode/1046.Last-Stone-Weight/main.go @@ -0,0 +1,67 @@ +package laststoneweight + +import ( + "container/heap" + "fmt" + "sort" +) + +/* +// IntSlice attaches the methods of Interface to []int, sorting in increasing order. +type IntSlice []int + +func (x IntSlice) Len() int { return len(x) } +func (x IntSlice) Less(i, j int) bool { return x[i] < x[j] } +func (x IntSlice) Swap(i, j int) { x[i], x[j] = x[j], x[i] } + +// Sort is a convenience method: x.Sort() calls Sort(x). +func (x IntSlice) Sort() { Sort(x) } +*/ + +type hp struct { + sort.IntSlice +} + +func (h hp) Less(i, j int) bool { + // ๅคงๅˆฐๅฐๆŽ’ๅบ + return h.IntSlice[i] > h.IntSlice[j] +} + +func (h *hp) Push(v interface{}) { + h.IntSlice = append(h.IntSlice, v.(int)) +} + +func (h *hp) Pop() interface{} { + old := h.IntSlice + v := old[len(old)-1] + h.IntSlice = old[:len(old)-1] + return v +} + +func (h *hp) PushInt(v int) { + heap.Push(h, v) +} + +func (h *hp) PopInt() int { + return heap.Pop(h).(int) +} + +// ๆ™‚้–“่ค‡้›œ O(nlogn), ็ฉบ้–“่ค‡้›œ O(n) +// n ๆ˜ฏ็Ÿณ้ ญๆ•ธ้‡. ๆฏๆฌกๅพž้šŠๅˆ—ไธญๅ–ๅ‡บๅ…ƒ็ด ้œ€่ฆ่ฉฑO(logn) ็š„ๆ™‚้–“, ๆœ€ๅคšๅ…ฑ้œ€่ฆ้œ€่ฆ็ฒ‰็ขŽ nโˆ’1 ๆฌก็Ÿณ้ ญ +func LastStoneWeight(stones []int) int { + q := &hp{stones} + heap.Init(q) + fmt.Println(q) + for q.Len() > 1 { + fmt.Println(q) + x, y := q.PopInt(), q.PopInt() + fmt.Printf("%d,%d\n", x, y) + if x > y { + q.PushInt(x - y) + } + } + if q.Len() > 0 { + return q.IntSlice[0] + } + return 0 +} diff --git a/Leetcode/1046.Last-Stone-Weight/main_test.go b/Leetcode/1046.Last-Stone-Weight/main_test.go new file mode 100644 index 000000000..3d34f3495 --- /dev/null +++ b/Leetcode/1046.Last-Stone-Weight/main_test.go @@ -0,0 +1,34 @@ +package laststoneweight + +import "testing" + +var tests = []struct { + arg1 []int + want int +}{ + { + []int{2, 7, 4, 1, 8, 1}, + 1, + }, +} + +func TestLastStoneWeight(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + if got := LastStoneWeight(tt.arg1); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLastStoneWeight(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LastStoneWeight(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/1046.Last-Stone-Weight -bench=. + +*/ diff --git a/Leetcode/1143.Longest-Common-Subsequence/index.html b/Leetcode/1143.Longest-Common-Subsequence/index.html new file mode 100644 index 000000000..0ead70434 --- /dev/null +++ b/Leetcode/1143.Longest-Common-Subsequence/index.html @@ -0,0 +1,3903 @@ + + + + + + + 1143.Longest Common Subsequence ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          + + + + + + + + +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                                          1143. Longest Common Subsequence

                                                                                                                                                                                                                                          題目

                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          For example, "ace" is a subsequence of "abcde". +A common subsequence of two strings is a subsequence that is common to both strings.

                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          Example 1:

                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          Input: text1 = "abcde", text2 = "ace" 
                                                                                                                                                                                                                                          +Output: 3  
                                                                                                                                                                                                                                          +Explanation: The longest common subsequence is "ace" and its length is 3.
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          Example 2:

                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          Input: text1 = "abc", text2 = "abc"
                                                                                                                                                                                                                                          +Output: 3
                                                                                                                                                                                                                                          +Explanation: The longest common subsequence is "abc" and its length is 3.
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          Example 3:

                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          Input: text1 = "abc", text2 = "def"
                                                                                                                                                                                                                                          +Output: 0
                                                                                                                                                                                                                                          +Explanation: There is no such common subsequence, so the result is 0.
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          Constraints:

                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                          • 1 <= text1.length, text2.length <= 1000
                                                                                                                                                                                                                                          • +
                                                                                                                                                                                                                                          • text1 and text2 consist of only lowercase English characters.
                                                                                                                                                                                                                                          • +
                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          題目大意

                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          給兩個string 求出, 這兩個string 的最長公共子序列的長度, 如果不存在返回0. +譬如 str1="abcde", str2="aceb", 輸出為3, 因為最長公共子序列是"ace"

                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          解題思路

                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                          1. 暴力解法, 用遞迴 dp(i,j) 表示 s1[0..i]和s2[0..j]中最長公共子序列的長度, +如果s1[i]==s2[j], 說明這個公共字符一定在lcs中, 如果知道了s1[0..i-1]和s2[0..j-1]中的lcs長度, 再加1就是s1[0..i]和s2[0..j]中lcs的長度

                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                             if (str[i] == str2[j]) {
                                                                                                                                                                                                                                            +     dp(i,j) = dp(i-1,j-1)+1
                                                                                                                                                                                                                                            + }
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            如果s1[i]!=s2[j], 說明這兩個字符至少有一個不在lcs中,

                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                             if (str[i] != str2[j]){
                                                                                                                                                                                                                                            +     dp(i,j) = max( dp(i-1,j) , dp(i,j-1))
                                                                                                                                                                                                                                            + }
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                             def longestCommonSubsequence(str1,str2) ->int:
                                                                                                                                                                                                                                            +     def dp(i,j):
                                                                                                                                                                                                                                            +         # 空的base code
                                                                                                                                                                                                                                            +         if i == -1 or j == -1:
                                                                                                                                                                                                                                            +             return 0
                                                                                                                                                                                                                                            +         if str[i] == str2[j]:
                                                                                                                                                                                                                                            +             # 找到一個lcs中的元素
                                                                                                                                                                                                                                            +             return dp(i-1, j-1)+1
                                                                                                                                                                                                                                            +         if str[i] != str2[j]:
                                                                                                                                                                                                                                            +             # 至少有一個字符不在lcs中, 都試一下,看誰能讓lcs最長
                                                                                                                                                                                                                                            +             return max( dp(i-1,j) , dp(i,j-1))
                                                                                                                                                                                                                                            +     return dp(len(str1)-1,len(str2)-1)
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                          2. +
                                                                                                                                                                                                                                          3. DP優化

                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                          4. +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          int longestCommonSubsequence(string str1, string str2) {
                                                                                                                                                                                                                                          +    int m = str1.size(), n = str2.size();
                                                                                                                                                                                                                                          +    // 定義對s1[0..i-1] 和 s2[0..j-1], 他們的lcs長度是dp[i][j]
                                                                                                                                                                                                                                          +    vector> dp(m + 1, vector(n + 1, 0));
                                                                                                                                                                                                                                          +    // base case: dp[0][...] = dp[..][0] = 0, 已初始化
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +    for (int i = 1; i 
                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          來源

                                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                                          解答

                                                                                                                                                                                                                                          +

                                                                                                                                                                                                                                          https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/1143.Longest-Common-Subsequence/main.go

                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          package longestcommonsubsequence
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +func LongestCommonSubsequence(text1 string, text2 string) int {
                                                                                                                                                                                                                                          +    var dp func(int, int) int
                                                                                                                                                                                                                                          +    dp = func(i, j int) int {
                                                                                                                                                                                                                                          +        if i == -1 || j == -1 {
                                                                                                                                                                                                                                          +            return 0
                                                                                                                                                                                                                                          +        }
                                                                                                                                                                                                                                          +        if text1[i] == text2[j] {
                                                                                                                                                                                                                                          +            return dp(i-1, j-1) + 1
                                                                                                                                                                                                                                          +        }
                                                                                                                                                                                                                                          +        if text1[i] != text2[j] {
                                                                                                                                                                                                                                          +            return max(dp(i-1, j), dp(i, j-1))
                                                                                                                                                                                                                                          +        }
                                                                                                                                                                                                                                          +        return 0
                                                                                                                                                                                                                                          +    }
                                                                                                                                                                                                                                          +    return dp(len(text1)-1, len(text2)-1)
                                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +func LongestCommonSubsequenceDP(text1 string, text2 string) int {
                                                                                                                                                                                                                                          +    m, n := len(text1), len(text2)
                                                                                                                                                                                                                                          +    if m == 0 || n == 0 {
                                                                                                                                                                                                                                          +        return 0
                                                                                                                                                                                                                                          +    }
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +    dp := make([][]int, m+1)
                                                                                                                                                                                                                                          +    for i := range dp {
                                                                                                                                                                                                                                          +        dp[i] = make([]int, n+1)
                                                                                                                                                                                                                                          +    }
                                                                                                                                                                                                                                          +    for i := 1; i <= 1="" m;="" i++="" {="" for="" j="" :="1;" <="n;" j++="" if="" text1[i-1]="=" text2[j-1]="" dp[i][j]="dp[i-1][j-1]" +="" }="" else="" dp[i-1][j])="" return="" dp[m][n]="" func="" max(a,="" b="" int)="" int="" a=""> b {
                                                                                                                                                                                                                                          +        return a
                                                                                                                                                                                                                                          +    }
                                                                                                                                                                                                                                          +    return b
                                                                                                                                                                                                                                          +}
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          goos: darwin
                                                                                                                                                                                                                                          +goarch: amd64
                                                                                                                                                                                                                                          +pkg: LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence
                                                                                                                                                                                                                                          +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz
                                                                                                                                                                                                                                          +BenchmarkLongestCommonSubsequence-8                  100         737158262 ns/op               0 B/op          0 allocs/op
                                                                                                                                                                                                                                          +BenchmarkLongestCommonSubsequenceDP-8            2355297               491.3 ns/op           912 B/op          8 allocs/op
                                                                                                                                                                                                                                          +PASS
                                                                                                                                                                                                                                          +ok      LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence 75.400s
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          + +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                          + +

                                                                                                                                                                                                                                          results matching ""

                                                                                                                                                                                                                                          +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                                            No results matching ""

                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            + + + + + + +
                                                                                                                                                                                                                                            + + +
                                                                                                                                                                                                                                            + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/1143.Longest-Common-Subsequence/main.go b/Leetcode/1143.Longest-Common-Subsequence/main.go new file mode 100644 index 000000000..c313aa34b --- /dev/null +++ b/Leetcode/1143.Longest-Common-Subsequence/main.go @@ -0,0 +1,48 @@ +package longestcommonsubsequence + +func LongestCommonSubsequence(text1 string, text2 string) int { + var dp func(int, int) int + dp = func(i, j int) int { + if i == -1 || j == -1 { + return 0 + } + if text1[i] == text2[j] { + return dp(i-1, j-1) + 1 + } + if text1[i] != text2[j] { + return max(dp(i-1, j), dp(i, j-1)) + } + return 0 + } + return dp(len(text1)-1, len(text2)-1) +} + +// DP table ๅ„ชๅŒ– +func LongestCommonSubsequenceDP(text1 string, text2 string) int { + m, n := len(text1), len(text2) + if m == 0 || n == 0 { + return 0 + } + + dp := make([][]int, m+1) + for i := range dp { + dp[i] = make([]int, n+1) + } + for i := 1; i <= m; i++ { + for j := 1; j <= n; j++ { + if text1[i-1] == text2[j-1] { + dp[i][j] = dp[i-1][j-1] + 1 + } else { + dp[i][j] = max(dp[i][j-1], dp[i-1][j]) + } + } + } + return dp[m][n] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/Leetcode/1143.Longest-Common-Subsequence/main_test.go b/Leetcode/1143.Longest-Common-Subsequence/main_test.go new file mode 100644 index 000000000..6b2407bf3 --- /dev/null +++ b/Leetcode/1143.Longest-Common-Subsequence/main_test.go @@ -0,0 +1,74 @@ +package longestcommonsubsequence + +import ( + "testing" +) + +var tests = []struct { + arg1 string + arg2 string + want int +}{ + { + "abcde", + "ace", + 3, + }, + { + "abc", + "abc", + 3, + }, + { + "abc", + "def", + 0, + }, + { + "pmjghexybyrgzczy", + "hafcdqbgncrcbihkd", + 4, + }, +} + +func TestLongestCommonSubsequence(t *testing.T) { + for _, tt := range tests { + if got := LongestCommonSubsequence(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func TestLongestCommonSubsequenceDP(t *testing.T) { + for _, tt := range tests { + if got := LongestCommonSubsequenceDP(tt.arg1, tt.arg2); got != tt.want { + t.Errorf("got = %v, want = %v", got, tt.want) + } + } +} + +func BenchmarkLongestCommonSubsequence(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestCommonSubsequence(tests[i%4].arg1, tests[i%4].arg2) + } +} + +func BenchmarkLongestCommonSubsequenceDP(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + LongestCommonSubsequenceDP(tests[i%4].arg1, tests[i%4].arg2) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence -bench=. +goos: darwin +goarch: amd64 +pkg: LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence +cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz +BenchmarkLongestCommonSubsequence-8 100 737158262 ns/op 0 B/op 0 allocs/op +BenchmarkLongestCommonSubsequenceDP-8 2355297 491.3 ns/op 912 B/op 8 allocs/op +PASS +ok LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence 75.400s +*/ diff --git a/Leetcode/1195.Fizz-Buzz-Multithreaded/index.html b/Leetcode/1195.Fizz-Buzz-Multithreaded/index.html new file mode 100644 index 000000000..1c68921cd --- /dev/null +++ b/Leetcode/1195.Fizz-Buzz-Multithreaded/index.html @@ -0,0 +1,3862 @@ + + + + + + + 1195. Fizz Buzz Multithreaded ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            + + + + + + + + +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                                            1195. Fizz Buzz Multithreaded

                                                                                                                                                                                                                                            題目

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            You have the four functions:

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            printFizz that prints the word "fizz" to the console, +printBuzz that prints the word "buzz" to the console, +printFizzBuzz that prints the word "fizzbuzz" to the console, and +printNumber that prints a given integer to the console. +You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads:

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            Thread A: calls fizz() that should output the word "fizz". +Thread B: calls buzz() that should output the word "buzz". +Thread C: calls fizzbuzz() that should output the word "fizzbuzz". +Thread D: calls number() that should only output the integers. +Modify the given class to output the series [1, 2, "fizz", 4, "buzz", ...] where the ith token (1-indexed) of the series is:

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            "fizzbuzz" if i is divisible by 3 and 5, +"fizz" if i is divisible by 3 and not 5, +"buzz" if i is divisible by 5 and not 3, or +i if i is not divisible by 3 or 5. +Implement the FizzBuzz class:

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            FizzBuzz(int n) Initializes the object with the number n that represents the length of the sequence that should be printed. +void fizz(printFizz) Calls printFizz to output "fizz". +void buzz(printBuzz) Calls printBuzz to output "buzz". +void fizzbuzz(printFizzBuzz) Calls printFizzBuzz to output "fizzbuzz". +void number(printNumber) Calls printnumber to output the numbers.

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            Example 1:

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            Input: n = 15 +Output: [1,2,"fizz",4,"buzz","fizz",7,8,"fizz","buzz",11,"fizz",13,14,"fizzbuzz"] +Example 2:

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            Input: n = 5 +Output: [1,2,"fizz",4,"buzz"]

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            Constraints:

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            1 <= n <= 50

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            題目大意

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            解題思路

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            Big O

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            時間複雜 : 空間複雜 :

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            來源

                                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                                            解答

                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/1195.Fizz-Buzz-Multithreaded/main.go

                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            package fizzbuzzmultithreaded
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +import (
                                                                                                                                                                                                                                            +    "fmt"
                                                                                                                                                                                                                                            +    "sync"
                                                                                                                                                                                                                                            +)
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +var (
                                                                                                                                                                                                                                            +    wg = sync.WaitGroup{}
                                                                                                                                                                                                                                            +)
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +// 時間複雜 O(), 空間複雜 O()
                                                                                                                                                                                                                                            +func FizzBuzz(n int) {
                                                                                                                                                                                                                                            +    fb := NewFizzBuzz()
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +    wg.Add(4)
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +    go fb.fizz()
                                                                                                                                                                                                                                            +    go fb.buzz()
                                                                                                                                                                                                                                            +    go fb.fizzbuzz()
                                                                                                                                                                                                                                            +    go fb.number()
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +    for i := 1; i 
                                                                                                                                                                                                                                            +

                                                                                                                                                                                                                                            Benchmark

                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            + +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                            + +

                                                                                                                                                                                                                                            results matching ""

                                                                                                                                                                                                                                            +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                                              No results matching ""

                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              + + + + + + + + + + +
                                                                                                                                                                                                                                              + + +
                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Leetcode/1195.Fizz-Buzz-Multithreaded/main.go b/Leetcode/1195.Fizz-Buzz-Multithreaded/main.go new file mode 100644 index 000000000..8c23be8f3 --- /dev/null +++ b/Leetcode/1195.Fizz-Buzz-Multithreaded/main.go @@ -0,0 +1,112 @@ +package fizzbuzzmultithreaded + +import ( + "fmt" + "sync" +) + +var ( + wg = sync.WaitGroup{} +) + +// ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() +func FizzBuzz(n int) { + fb := NewFizzBuzz() + + wg.Add(4) + + go fb.fizz() + go fb.buzz() + go fb.fizzbuzz() + go fb.number() + + for i := 1; i <= n; i++ { + if i%3 == 0 && i%5 == 0 { + fb.fizzbuzzCh <- struct{}{} + } else if i%3 == 0 { + fb.fizzCh <- struct{}{} + } else if i%5 == 0 { + fb.buzzCh <- struct{}{} + } else { + fb.numberCh <- i + } + <-fb.orderCh + } + fb.done <- struct{}{} + fb.done <- struct{}{} + fb.done <- struct{}{} + fb.done <- struct{}{} + wg.Wait() +} + +type FizzBuzzStruct struct { + numberCh chan int + fizzCh chan struct{} + buzzCh chan struct{} + fizzbuzzCh chan struct{} + orderCh chan struct{} + done chan struct{} +} + +func NewFizzBuzz() *FizzBuzzStruct { + return &FizzBuzzStruct{ + numberCh: make(chan int), + fizzCh: make(chan struct{}), + buzzCh: make(chan struct{}), + fizzbuzzCh: make(chan struct{}), + orderCh: make(chan struct{}), + done: make(chan struct{}, 4), + } +} + +func (fb *FizzBuzzStruct) fizz() { + defer wg.Done() + for { + select { + case <-fb.fizzCh: + fmt.Print("fizz") + fb.orderCh <- struct{}{} + case <-fb.done: + return + } + } +} + +func (fb *FizzBuzzStruct) buzz() { + defer wg.Done() + for { + select { + case <-fb.buzzCh: + fmt.Print("buzz") + fb.orderCh <- struct{}{} + case <-fb.done: + return + } + } +} + +func (fb *FizzBuzzStruct) fizzbuzz() { + defer wg.Done() + for { + select { + case <-fb.fizzbuzzCh: + fmt.Print("fizzbuzz") + fb.orderCh <- struct{}{} + case <-fb.done: + return + } + } +} + +func (fb *FizzBuzzStruct) number() { + defer wg.Done() + for { + select { + case v := <-fb.numberCh: + fmt.Print(v) + fb.orderCh <- struct{}{} + case <-fb.done: + return + } + } +} diff --git a/Leetcode/1195.Fizz-Buzz-Multithreaded/main_test.go b/Leetcode/1195.Fizz-Buzz-Multithreaded/main_test.go new file mode 100644 index 000000000..b10e54af9 --- /dev/null +++ b/Leetcode/1195.Fizz-Buzz-Multithreaded/main_test.go @@ -0,0 +1,35 @@ +package fizzbuzzmultithreaded + +import "testing" + +var tests = []struct { + arg1 int + want []interface{} +}{ + { + 15, + []interface{}{1, 2, "fizz", 4, "buzz", "fizz", 7, 8, "fizz", "buzz", 11, "fizz", 13, 14, "fizzbuzz"}, + }, +} + +func TestFizzBuzz(t *testing.T) { + for _, tt := range tests { + // if got := ReverseList(tt.arg1); !reflect.DeepEqual(got, tt.want) { + // if got := FizzBuzz(tt.arg1); got != tt.want { + // t.Errorf("got = %v, want = %v", got, tt.want) + // } + FizzBuzz(tt.arg1) + } +} + +func BenchmarkFizzBuzz(b *testing.B) { + b.ResetTimer() + for i := 0; i < b.N; i++ { + FizzBuzz(tests[0].arg1) + } +} + +/* +go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. + +*/ diff --git "a/Leetcode_labuladong/1.\344\270\244\346\225\260\344\271\213\345\222\214.go" "b/Leetcode_labuladong/1.\344\270\244\346\225\260\344\271\213\345\222\214.go" new file mode 100644 index 000000000..c77cbf969 --- /dev/null +++ "b/Leetcode_labuladong/1.\344\270\244\346\225\260\344\271\213\345\222\214.go" @@ -0,0 +1,22 @@ +/* + * @lc app=leetcode.cn id=1 lang=golang + * + * [1] ไธคๆ•ฐไน‹ๅ’Œ + */ + +// @lc code=start +// ็”จไธ€ๅ€‹map, key็ด€้Œ„number็š„ๅ€ผ, value ็ด€้Œ„number็š„index +// ้ๆญทๆ•ดๅ€‹nums, ๅˆคๆ–ทmapไธญๆ˜ฏๅฆๆœ‰ "target-number"ๅญ˜ๅ…ฅmap, ๅฆ‚ๆžœๆœ‰ๅฐฑๅฏไปฅๅฐ‡ indexๅพžmapๅ–ๅ‡บ, ไธฆๅ›žๅ‚ณ +func twoSum(nums []int, target int) []int { + m := make(map[int]int) + for i, v := range nums { + if j, ok := m[target-v]; ok { + return []int{j, i} + } + m[v] = i + } + return nil +} + +// @lc code=end + diff --git "a/Leetcode_labuladong/143.\351\207\215\346\216\222\351\223\276\350\241\250.go" "b/Leetcode_labuladong/143.\351\207\215\346\216\222\351\223\276\350\241\250.go" new file mode 100644 index 000000000..40769930c --- /dev/null +++ "b/Leetcode_labuladong/143.\351\207\215\346\216\222\351\223\276\350\241\250.go" @@ -0,0 +1,62 @@ +// ๆ™‚้–“่ค‡้›œๅบฆ: +// ็ฉบ้–“่ค‡้›œๅบฆ: +/* + * @lc app=leetcode.cn id=143 lang=golang + * + * [143] ้‡ๆŽ’้“พ่กจ + */ + +// @lc code=start +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ + +// ๅ…ˆ็”จๅฟซๆ…ขๆŒ‡้‡ๆ‰พๅ‡บLinked list็š„ไธญ้–“้ปž +// ็„ถๅพŒๆŠŠLinked listๅˆ†ๆˆๅ…ฉๅŠ +// ๅ†ๆŠŠๅพŒๅŠ็š„Linked listๅ่ฝ‰ +// ๅ†ๆŠŠๅ…ฉๅŠ็š„Linked list merge ่ตทไพ† +func reorderList(head *ListNode) { + mid := middleNode(head) + + // 2.ๅ่ฝ‰ไธญ้–“็ฏ€้ปž็š„ไธ‹ไธ€ๅ€‹็ฏ€้ปž + right := resverseNode(mid.Next) + mid.Next = nil + left := head + mergeNode(left, right) +} + +// [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) +func middleNode(head *ListNode) *ListNode { + slow, fast := head, head + for fast != nil && fast.Next != nil { + slow = slow.Next + fast = fast.Next.Next + } + return slow +} + +// [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) +func resverseNode(head *ListNode) *ListNode { + var pre *ListNode + for head != nil { + tmp := head.Next + head.Next = pre + pre = head + head = tmp + } + return pre +} + +func mergeNode(l1, l2 *ListNode) { + lcur, rcur := l1, l2 + for lcur != nil && rcur != nil { + lcur.Next, rcur.Next, lcur, rcur = rcur, lcur.Next, lcur.Next, rcur.Next + } +} + +// @lc code=end + diff --git "a/Leetcode_labuladong/19.\345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254-n-\344\270\252\347\273\223\347\202\271.go" "b/Leetcode_labuladong/19.\345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254-n-\344\270\252\347\273\223\347\202\271.go" new file mode 100644 index 000000000..055cc1de4 --- /dev/null +++ "b/Leetcode_labuladong/19.\345\210\240\351\231\244\351\223\276\350\241\250\347\232\204\345\200\222\346\225\260\347\254\254-n-\344\270\252\347\273\223\347\202\271.go" @@ -0,0 +1,37 @@ +// ๆ™‚้–“่ค‡้›œๅบฆ: +// ็ฉบ้–“่ค‡้›œๅบฆ: +/* + * @lc app=leetcode.cn id=19 lang=golang + * + * [19] ๅˆ ้™ค้“พ่กจ็š„ๅ€’ๆ•ฐ็ฌฌ N ไธช็ป“็‚น + */ + +// @lc code=start +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +// ็”ข็”Ÿ dummyHead,่ทŸ preslow +// ไฝฟ็”จ้›™ๆŒ‡้‡, ๅ…ˆ่ฎ“ fast่ตฐ `k` ๆญฅ, ็„ถๅพŒ `fast slow ๅŒ้€Ÿๅ‰้€ฒ` +// ้€™ๆจฃ็•ถfast่ตฐๅˆฐnilๆ™‚, slowๆ‰€ๅœจไฝ็ฝฎๅฐฑๆ˜ฏๅœจๅ€’ๆ•ธ็ฌฌ k ็š„็ฏ€้ปž +// ๅฐ‡ slow็š„ๅ‰ไธ€ๆญฅ(preslow)็š„next ๆŒ‡ๅ‘ slow.Next +func removeNthFromEnd(head *ListNode, n int) *ListNode { + dummyHead := &ListNode{Next: head} + preSlow, slow, fast := dummyHead, head, head + for fast != nil { + if n <= 0 { + preSlow = slow + slow = slow.Next + } + fast = fast.Next + n-- + } + preSlow.Next = slow.Next + return dummyHead.Next +} + +// @lc code=end + diff --git "a/Leetcode_labuladong/2.\344\270\244\346\225\260\347\233\270\345\212\240.go" "b/Leetcode_labuladong/2.\344\270\244\346\225\260\347\233\270\345\212\240.go" new file mode 100644 index 000000000..11d88b753 --- /dev/null +++ "b/Leetcode_labuladong/2.\344\270\244\346\225\260\347\233\270\345\212\240.go" @@ -0,0 +1,50 @@ +// ๆ™‚้–“่ค‡้›œๅบฆ: +// ็ฉบ้–“่ค‡้›œๅบฆ: +/* + * @lc app=leetcode.cn id=2 lang=golang + * + * [2] ไธคๆ•ฐ็›ธๅŠ  + */ + +// @lc code=start +/** + * Definition for singly-linked list. + * type ListNode struct { + * Val int + * Next *ListNode + * } + */ +// ้ๆญท l1่ทŸ l2. ่ฌ›ๅ…ฉๅ€‹list็š„val็›ธๅŠ , ไธฆไธ”่จ˜้Œ„้€ฒไฝ็š„ๅ€ผ็ตฆnextไฝฟ็”จ +// ๆœ€ๅพŒๅฆ‚ๆžœ carry ้‚„ๆœ‰็š„่ฉฑ, ้œ€่ฆ็”ข็”Ÿไธ€ๅ€‹ๆ–ฐ็š„็ฏ€้ปž +func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { + var result, tail *ListNode + carry := 0 + for l1 != nil || l2 != nil { + n1, n2 := 0, 0 + if l1 != nil { + n1 = l1.Val + l1 = l1.Next + } + if l2 != nil { + n2 = l2.Val + l2 = l2.Next + } + + sum := n1 + n2 + carry + sum, carry = sum%10, sum/10 + if result == nil { + result = &ListNode{Val: sum} + tail = result + } else { + tail.Next = &ListNode{Val: sum} + tail = tail.Next + } + } + if carry > 0 { + tail.Next = &ListNode{Val: carry} + } + return result +} + +// @lc code=end + diff --git "a/Leetcode_labuladong/5.\346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262.go" "b/Leetcode_labuladong/5.\346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262.go" new file mode 100644 index 000000000..5f9a2ffd5 --- /dev/null +++ "b/Leetcode_labuladong/5.\346\234\200\351\225\277\345\233\236\346\226\207\345\255\220\344\270\262.go" @@ -0,0 +1,40 @@ +// ๆ™‚้–“่ค‡้›œๅบฆ: +// ็ฉบ้–“่ค‡้›œๅบฆ: +/* + * @lc app=leetcode.cn id=5 lang=golang + * + * [5] ๆœ€้•ฟๅ›žๆ–‡ๅญไธฒ + */ + +// @lc code=start +func longestPalindrome(s string) string { + dp := make([][]bool, len(s)) + result := s[0:1] + + for i := 0; i < len(s); i++ { + dp[i] = make([]bool, len(s)) + dp[i][i] = true // ๆฏๅ€‹ๅญ—็ฌฆๆœฌ่บซ้ƒฝๆ˜ฏๅ›žๆ–‡ + } + for length := 2; length <= len(s); length++ { + for start := 0; start < len(s)-length+1; start++ { + end := start + length - 1 + if s[start] != s[end] { + // ๅญ—้ ญๅญ—ๅฐพไธๅŒ, ไธๆ˜ฏๅ›žๆ–‡ + continue + } else if length < 3 { + // ้•ทๅบฆ็‚บ2ไธ”ๅญ—้ ญๅญ—ๅฐพ็›ธๅŒ, ๅ‰‡็‚บๅ›žๆ–‡ + dp[start][end] = true + } else { + // ็‹€ๆ…‹่ฝ‰็งป : ๅŽปๆŽ‰ๅญ—้ ญๅญ—ๅฐพ, ๅˆคๆ–ทๆ˜ฏๅฆ้‚„ๆ˜ฏๅ›žๆ–‡ + dp[start][end] = dp[start+1][end-1] + } + if dp[start][end] && (end-start+1) > len(result) { + result = s[start : end+1] + } + } + } + return result +} + +// @lc code=end + diff --git a/SUMMARY.md b/SUMMARY.md new file mode 100644 index 000000000..5c442237d --- /dev/null +++ b/SUMMARY.md @@ -0,0 +1,219 @@ +# Kimi's LeetcodeGolang Notes + +- Algorithms + - A 1 B 2 C 3 + * [A1B2C3: Two Go Routine Print A1B2C3....Z26](Algorithms/A1B2C3/README.md) + - Find Target Last Index + * [Find Target Last Index](Algorithms/Find_Target_Last_Index/findtargetlastindex.md) + - Intersection Of Two Sorted Arrays Using In Place Approach + * [Intersection Of Two Sorted Arrays Using In Place Approach](Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/README.md) + - Search Graph + * [Search Graph In Golang](Algorithms/SearchGraph/README.md) + - [Weighted Edit Distance](Algorithms/WeightedEditDistance/README.md) +- [Code Signal](CodeSignal/README.md) + - Bank Requests + * [Bank Requests](CodeSignal/Bank-Requests/README.md) +- Codility + - Lesson + - 0001.Iterations + - Binary Gap + * [Binary Gap](Codility/Lesson/0001.Iterations/Binary-Gap/README.md) + - 0002.Array + - Cyclic Rotation + * [Cyclic Rotation](Codility/Lesson/0002.Array/CyclicRotation/README.md) + - [Odd Occurrences In Array](Codility/Lesson/0002.Array/OddOccurrencesInArray/README.md) + - 0003.Time-Complexity + - [Frog Jmp](Codility/Lesson/0003.Time-Complexity/FrogJmp/README.md) + - [Perm Missing Elem](Codility/Lesson/0003.Time-Complexity/PermMissingElem/README.md) + - [Tape Equilibrium](Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/README.md) + - 0004.Counting-Elements + - [Frog River One](Codility/Lesson/0004.Counting-Elements/FrogRiverOne/README.md) + - [Max Counters](Codility/Lesson/0004.Counting-Elements/MaxCounters/README.md) + - [Missing Integer](Codility/Lesson/0004.Counting-Elements/MissingInteger/README.md) + - [Perm Check](Codility/Lesson/0004.Counting-Elements/PermCheck/README.md) + - 0005.Prefix-Sums + - [Count Div](Codility/Lesson/0005.Prefix-Sums/CountDiv/README.md) + - [Genomic Range Query](Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/README.md) + - [Min Avg Two Slice](Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/README.md) + - [Passing Cars](Codility/Lesson/0005.Prefix-Sums/PassingCars/README.md) + - 0006.Sorting + - [Distinct](Codility/Lesson/0006.Sorting/Distinct/README.md) + - [Max Product Of Three](Codility/Lesson/0006.Sorting/MaxProductOfThree/README.md) + - [Number Of Disc Intersections](Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/README.md) + - [Triangle](Codility/Lesson/0006.Sorting/Triangle/README.md) + - 0007.Stacks-and-Queues + - [Brackets](Codility/Lesson/0007.Stacks-and-Queues/Brackets/README.md) + - [Fish](Codility/Lesson/0007.Stacks-and-Queues/Fish/README.md) + - [Nesting](Codility/Lesson/0007.Stacks-and-Queues/Nesting/README.md) + - [Stone Wall](Codility/Lesson/0007.Stacks-and-Queues/StoneWall/README.md) + - 0008.Leader + - [Dominator](Codility/Lesson/0008.Leader/Dominator/README.md) + - [Equi Leader](Codility/Lesson/0008.Leader/EquiLeader/README.md) + - 0009.Maximum-Slice-Problem + - [Max Double Slice Sum](Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/README.md) + - [Max Profit](Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/README.md) + - [Max Slice Sum](Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/README.md) + - 0010.Prime-And-Composite-Numbers + - [Count Factors](Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/README.md) + - [Flags](Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/README.md) + - [Min Perimeter Rectangle](Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/README.md) + - [Peaks](Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/README.md) + - 0011.Sieve-of-Eratosthenes + - [Count Non Divisible](Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/README.md) + - [Count Semiprimes](Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/README.md) + - 0012.Euclidean-Algorithm + - [Chocolates By Numbers](Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/README.md) + - [Common Prime Divisors](Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/README.md) + - 0013.Fibonacci-Numbers + - [Fib Frog](Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/README.md) + - 0015.Caterpillar-Method + - [Abs Distinct](Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/README.md) +- Geeksfor Geeks + - Sorting Algorithms + - [0031.Find-Minimum-Difference-Between-Any-Two-Elements](GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/README.md) +- Leetcode + - 0000.xxxx + * [NUM.LEETCODETITLE](Leetcode/0000.xxxx/README.md) + - 0001.Two-Sum + - [Merging 2 Packages](Leetcode/0001.Two-Sum/Merging-2-Packages/README.md) + * [0001.Two Sum](Leetcode/0001.Two-Sum/README.md) + - 0002.Add-Two-Numbers + * [0002.Add Two Numbers](Leetcode/0002.Add-Two-Numbers/README.md) + - 0003.Longest-Substring-Without-Repeating-Characters + * [0003.Longest Substring Without Repeating Characters](Leetcode/0003.Longest-Substring-Without-Repeating-Characters/README.md) + - 0005.Longest-Palindromic-Substring + * [0005. Longest Palindromic Substring](Leetcode/0005.Longest-Palindromic-Substring/README.md) + - 0015.3Sum + * [0015. 3Sum](Leetcode/0015.3Sum/README.md) + - 0019.Remove-Nth-Node-From-End-of-List + * [0019. Remove Nth Node From End of List](Leetcode/0019.Remove-Nth-Node-From-End-of-List/README.md) + - 0020.Valid-Parentheses + * [0020. Valid Parentheses](Leetcode/0020.Valid-Parentheses/README.md) + - 0021.Merge-Two-Sorted-Lists + * [0021. Merge Two Sorted Lists](Leetcode/0021.Merge-Two-Sorted-Lists/README.md) + - 0027.Remove-Element + * [0027.Remove Element](Leetcode/0027.Remove-Element/README.md) + - 0028.Find-the-Index-of-the-First-Occurrence-in-a-String + * [0028. Find the Index of the First Occurrence in a String](Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/README.md) + - 0035.Search-Insert-Position + * [0035.Search Insert Position](Leetcode/0035.Search-Insert-Position/README.md) + - [0046.Permutations](Leetcode/0046.Permutations/README.md) + - 0049.Group-Anagrams + * [0049.Group Anagrams](Leetcode/0049.Group-Anagrams/README.md) + - 0053.Maximum-Subarray + * [0053.Maximum Subarray](Leetcode/0053.Maximum-Subarray/README.md) + - 0059.Spiral-Matrix-II + * [0059.Spiral Matrix II](Leetcode/0059.Spiral-Matrix-II/README.md) + - 0070.Climbing-Stairs + * [0070.Climbing Stairs](Leetcode/0070.Climbing-Stairs/README.md) + - 0072.Edit-Distance + * [0072. Edit Distance](Leetcode/0072.Edit-Distance/README.md) + - 0075.Sort-Colors + * [0075.Sort Colors](Leetcode/0075.Sort-Colors/README.md) + - 0078.Subsets + * [0078. Subsets](Leetcode/0078.Subsets/README.md) + - 0088.Merge-Sorted-Array + * [0088.Merge Sorted Array](Leetcode/0088.Merge-Sorted-Array/README.md) + - 0094.Binary-Tree-Inorder-Traversal + * [0094.Binary Tree Inorder Traversal](Leetcode/0094.Binary-Tree-Inorder-Traversal/README.md) + - 0100.Same-Tree + * [100. Same Tree](Leetcode/0100.Same-Tree/README.md) + - 0104.Maximum-Depth-of-Binary-Tree + * [0104.Maximum Depth of Binary Tree](Leetcode/0104.Maximum-Depth-of-Binary-Tree/README.md) + - 0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal + * [105. Construct Binary Tree from Preorder and Inorder Traversal](Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/README.md) + - 0110.Balanced-Binary-Tree + * [110. Balanced Binary Tree](Leetcode/0110.Balanced-Binary-Tree/README.md) + - 0121.Best-Time-to-Buy-and-Sell-Stock + * [0121.Best Time to Buy and Sell Stock](Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/README.md) + - 0125.Valid-Palindrome + * [0125. Valid Palindrome](Leetcode/0125.Valid-Palindrome/README.md) + - 0128.Longest-Consecutive-Sequence + * [128. Longest Consecutive Sequence](Leetcode/0128.Longest-Consecutive-Sequence/README.md) + - 0138.Copy-List-with-Random-Pointer + * [138. Copy List with Random Pointer](Leetcode/0138.Copy-List-with-Random-Pointer/README.md) + - 0141.Linked-List-Cycle + * [0141.Linked List Cycle](Leetcode/0141.Linked-List-Cycle/README.md) + - 0142.Linked-List-CycleII + * [0142.Linked List Cycle II](Leetcode/0142.Linked-List-CycleII/README.md) + - 0143.Reorder-List + * [143. Reorder List](Leetcode/0143.Reorder-List/README.md) + - 0167.Two-Sum-II-Input-Array-Is-Sorted + * [0167.Two Sum II Input Array Is Sorted](Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/README.md) + - 0203.Remove-Linked-List-Elements + * [0203.Remove Linked List Elements](Leetcode/0203.Remove-Linked-List-Elements/README.md) + - 0206.Reverse-Linked-List + * [206. Reverse Linked List](Leetcode/0206.Reverse-Linked-List/README.md) + - 0209.Minimum-Size-Subarray-Sum + * [0209. Minimum Size Subarray Sum](Leetcode/0209.Minimum-Size-Subarray-Sum/README.md) + - 0215.Kth-Largest-Element-in-an-Array + * [0215. Kth Largest Element in an Array](Leetcode/0215.Kth-Largest-Element-in-an-Array/README.md) + - [0217.Contains-Duplicate](Leetcode/0217.Contains-Duplicate/README.md) + - 0226.Invert-Binary-Tree + * [226. Invert Binary Tree](Leetcode/0226.Invert-Binary-Tree/README.md) + - 0238.Product-of-Array-Except-Self + * [238. Product of Array Except Self](Leetcode/0238.Product-of-Array-Except-Self/README.md) + - [0242.Valid-Anagram](Leetcode/0242.Valid-Anagram/README.md) + - 0283.Move-Zeroes + * [0283. Move Zeroes](Leetcode/0283.Move-Zeroes/README.md) + - 0300.Longest-Increasing-Subsequence + * [0300.Longest Increasing Subsequence](Leetcode/0300.Longest-Increasing-Subsequence/README.md) + - 0310.Minimum-Height-Trees + * [0310.Minimum Height Trees](Leetcode/0310.Minimum-Height-Trees/README.md) + - 0322.Coin-Change + * [0322.Coin Change](Leetcode/0322.Coin-Change/README.md) + - 0344.Reverse-String + * [0344.Reverse String](Leetcode/0344.Reverse-String/README.md) + - 0347.Top-K-Frequent-Elements + * [347. Top K Frequent Elements](Leetcode/0347.Top-K-Frequent-Elements/README.md) + - 0354.Russian-Doll-Envelopes + * [0354. Russian Doll Envelope](Leetcode/0354.Russian-Doll-Envelopes/README.md) + - 0380.Insert-Delete-GetRandom-O1 + * [380. Insert Delete GetRandom O(1)](Leetcode/0380.Insert-Delete-GetRandom-O1/README.md) + - 0381.Insert-Delete-GetRandom-O1-Duplicates-allowed + * [381.Insert Delete GetRandom O(1) Duplicates allowed](Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/README.md) + - 0409.Longest-Palindrome + * [0409. Longest Palindrome](Leetcode/0409.Longest-Palindrome/README.md) + - 0412.Fizz-Buzz + * [412. Fizz Buzz](Leetcode/0412.Fizz-Buzz/README.md) + - 0438.Find-All-Anagrams-in-a-String + * [0438.Find All Anagrams in a String](Leetcode/0438.Find-All-Anagrams-in-a-String/README.md) + - 0509.Fibonacci-Number + * [0509.Fibonacci Number](Leetcode/0509.Fibonacci-Number/README.md) + - 0516.Longest-Palindromic-Subsequence + * [516. Longest Palindromic Subsequence](Leetcode/0516.Longest-Palindromic-Subsequence/README.md) + - 0543.Diameter-of-Binary-Tree + * [0543. Diameter of Binary Tree](Leetcode/0543.Diameter-of-Binary-Tree/README.md) + - 0567.Permutation-in-String + * [0567.Permutation in String](Leetcode/0567.Permutation-in-String/README.md) + - 0693.Binary-Number-with-Alternating-Bits + * [0693.Binary Number with Alternating Bits](Leetcode/0693.Binary-Number-with-Alternating-Bits/README.md) + - 0695.Max-Area-of-Island + * [0695.Max Area of Island](Leetcode/0695.Max-Area-of-Island/README.md) + - 0703.Kth-Largest-Element-in-a-Stream + * [0703. Kth Largest Element in a Stream](Leetcode/0703.Kth-Largest-Element-in-a-Stream/README.md) + - 0704.Binary-Search + * [0704.Binary Search](Leetcode/0704.Binary-Search/README.md) + - 0721.Accounts-Merge + * [0721.Accounts Merge](Leetcode/0721.Accounts-Merge/README.md) + - 0733.Flood-Fill + * [0733.Flood Fill](Leetcode/0733.Flood-Fill/README.md) + - 0746.Min-Cost-Climbing-Stairs + * [746. Min Cost Climbing Stairs](Leetcode/0746.Min-Cost-Climbing-Stairs/README.md) + - 0752.Open-the-Lock + * [0752.Open the Lock](Leetcode/0752.Open-the-Lock/README.md) + - 0876.Middle-of-the-Linked-List + * [0876.Middle of the Linked List](Leetcode/0876.Middle-of-the-Linked-List/README.md) + - 1046.Last-Stone-Weight + * [1046. Last Stone Weight](Leetcode/1046.Last-Stone-Weight/README.md) + - 1143.Longest-Common-Subsequence + * [1143.Longest Common Subsequence](Leetcode/1143.Longest-Common-Subsequence/README.md) + - 1195.Fizz-Buzz-Multithreaded + * [1195. Fizz Buzz Multithreaded](Leetcode/1195.Fizz-Buzz-Multithreaded/README.md) +- [Structures](structures/README.md) + - Heap + * [Golang Container Heap](structures/heap/index.en.md) +- [Template](template/README.md) +* [CHANGELOG](CHANGELOG.md) +* [Content](Content.md) +* [Tags](tags.md) diff --git a/Utility/crud/crud.go b/Utility/crud/crud.go new file mode 100644 index 000000000..b4cebd1de --- /dev/null +++ b/Utility/crud/crud.go @@ -0,0 +1,135 @@ +package crud + +import ( + "bytes" + "crypto/tls" + "errors" + "fmt" + "io/ioutil" + "net/http" + + jsoniter "github.com/json-iterator/go" +) + +var ( + errStatusNo200 = errors.New("http code not 200") +) + +type Crud struct { + URL string + Request +} + +type Request struct { + Header map[string]string + Params map[string]string + Body map[string]interface{} +} + +type Response struct { + HttpCode int + Response string + Header http.Header + Error error +} + +func NewCrud(url string) *Crud { + return &Crud{URL: url} +} + +func handleRequest(url string, method string, header map[string]string, params map[string]string, body map[string]interface{}) (int, string, http.Header, error) { + // body + var json = jsoniter.ConfigCompatibleWithStandardLibrary + jsonStr, _ := json.Marshal(body) + + // ignore SSL + http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + + req, err := http.NewRequest(method, url, bytes.NewBuffer(jsonStr)) + if err != nil { + return 0, "", nil, err + } + + // headers + for key, value := range header { + req.Header.Add(key, value) + } + + // params + q := req.URL.Query() + for key, value := range params { + q.Add(key, value) + } + + client := &http.Client{} + + req.URL.RawQuery = q.Encode() + + resp, err := client.Do(req) + + if err != nil { + fmt.Println(err) + } + defer resp.Body.Close() + + content, err := ioutil.ReadAll(resp.Body) + if err != nil { + return resp.StatusCode, "", nil, err + } + respBody := string(content) + headers := resp.Header + + return resp.StatusCode, respBody, headers, nil +} + +func (crud *Crud) Post() Response { + httpCode, response, headers, error := handleRequest(crud.URL, "POST", crud.Header, crud.Params, crud.Body) + + resp := Response{ + HttpCode: httpCode, + Response: response, + Header: headers, + Error: error, + } + + return resp +} + +func (crud *Crud) Get() Response { + httpCode, response, headers, error := handleRequest(crud.URL, "GET", crud.Header, crud.Params, crud.Body) + + resp := Response{ + HttpCode: httpCode, + Response: response, + Header: headers, + Error: error, + } + + return resp +} + +func (crud *Crud) Put() Response { + httpCode, response, headers, error := handleRequest(crud.URL, "PUT", crud.Header, crud.Params, crud.Body) + + resp := Response{ + HttpCode: httpCode, + Response: response, + Header: headers, + Error: error, + } + + return resp +} + +func (crud *Crud) Delete() Response { + httpCode, response, headers, error := handleRequest(crud.URL, "DELETE", crud.Header, crud.Params, crud.Body) + + resp := Response{ + HttpCode: httpCode, + Response: response, + Header: headers, + Error: error, + } + + return resp +} diff --git a/Utility/crud/crud_test.go b/Utility/crud/crud_test.go new file mode 100644 index 000000000..d96abe3cc --- /dev/null +++ b/Utility/crud/crud_test.go @@ -0,0 +1,74 @@ +package crud + +import ( + "fmt" + "testing" +) + +func TestPost(t *testing.T) { + tests := []struct { + name string + url string + header map[string]string + params map[string]string + body map[string]interface{} + }{ + { + name: "Post", + url: "https://10.36.235.47:7071/api/packages", + header: map[string]string{ + "Version": "1.1.0", + "Windows-Package-Manager": "winget-cli-restsource-dev", + "Content-Type": "application/json", + "Accept": "application/Json", + }, + params: nil, + body: map[string]interface{}{ + "PackageIdentifier": "Demo.Postman", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + crud := NewCrud(tt.url) + crud.Header = tt.header + crud.Params = tt.params + crud.Body = tt.body + if got := crud.Post(); got.Error != nil { + t.Errorf("got = %v", got) + } else { + fmt.Println(got.HttpCode) + } + }) + } +} + +func TestGet(t *testing.T) { + tests := []struct { + name string + url string + header map[string]string + params map[string]string + }{ + { + name: "Get", + url: "https://kimi0230.github.io", + header: nil, + params: nil, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + crud := NewCrud(tt.url) + crud.Header = tt.header + crud.Params = tt.params + if got := crud.Get(); got.Error != nil { + t.Errorf("got = %v", got) + } else { + fmt.Println(got.HttpCode) + } + }) + } +} diff --git a/Utility/structures/StackBasedOnArray.go b/Utility/structures/StackBasedOnArray.go new file mode 100644 index 000000000..3436b624c --- /dev/null +++ b/Utility/structures/StackBasedOnArray.go @@ -0,0 +1,79 @@ +package structures + +import "fmt" + +/* +tree stack +*/ + +type ArrayStack struct { + //data + data []interface{} + //stack + top int +} + +func NewArrayStack() *ArrayStack { + return &ArrayStack{ + data: make([]interface{}, 0, 32), + top: -1, + } +} + +func (this *ArrayStack) IsEmpty() bool { + if this.top < 0 { + return true + } + return false +} + +func (this *ArrayStack) Push(v interface{}) { + if this.top < 0 { + this.top = 0 + } else { + this.top += 1 + } + + if this.top > len(this.data)-1 { + this.data = append(this.data, v) + } else { + this.data[this.top] = v + } +} + +func (this *ArrayStack) Pop() interface{} { + if this.IsEmpty() { + return nil + } + v := this.data[this.top] + this.top -= 1 + return v +} + +func (this *ArrayStack) Top() interface{} { + if this.IsEmpty() { + return nil + } + return this.data[this.top] +} + +func (this *ArrayStack) Flush() { + this.top = -1 +} + +func (this *ArrayStack) Size() int { + if this.top < 0 { + return 0 + } + return this.top + 1 +} + +func (this *ArrayStack) Print() { + if this.IsEmpty() { + fmt.Println("empty statck") + } else { + for i := this.top; i >= 0; i-- { + fmt.Println(this.data[i]) + } + } +} diff --git a/Utility/structures/TreeNode.go b/Utility/structures/TreeNode.go new file mode 100644 index 000000000..6c3750de9 --- /dev/null +++ b/Utility/structures/TreeNode.go @@ -0,0 +1,251 @@ +/* +https://github.com/halfrost/LeetCode-Go/tree/master/structures +*/ + +package structures + +import ( + "fmt" +) + +// TreeNode is tree's node +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +// NULL ๆ–นไพฟๆทปๅŠ ๆธฌ่ฉฆๆ•ธๆ“š +var NULL = -1 << 63 + +// Ints2TreeNode ๅˆฉ็”จ []int ็”Ÿๆˆ *TreeNode +func Ints2TreeNode(ints []int) *TreeNode { + n := len(ints) + if n == 0 { + return nil + } + + root := &TreeNode{ + Val: ints[0], + } + + queue := make([]*TreeNode, 1, n*2) + queue[0] = root + + i := 1 + for i < n { + node := queue[0] + queue = queue[1:] + + if i < n && ints[i] != NULL { + node.Left = &TreeNode{Val: ints[i]} + queue = append(queue, node.Left) + } + i++ + + if i < n && ints[i] != NULL { + node.Right = &TreeNode{Val: ints[i]} + queue = append(queue, node.Right) + } + i++ + } + + return root +} + +// GetTargetNode ่ฟ”ๅ›ž Val = target ็š„ TreeNode +// root ไธญไธ€ๅฎšๆœ‰ node.Val = target +func GetTargetNode(root *TreeNode, target int) *TreeNode { + if root == nil || root.Val == target { + return root + } + + res := GetTargetNode(root.Left, target) + if res != nil { + return res + } + return GetTargetNode(root.Right, target) +} + +func indexOf(val int, nums []int) int { + for i, v := range nums { + if v == val { + return i + } + } + + msg := fmt.Sprintf("%d ไธๅญ˜ๅœจๆ–ผ %v ไธญ", val, nums) + panic(msg) +} + +// PreIn2Tree ๆŠŠ preorder ๅ’Œ inorder slice ่ฝ‰ๆ›ๆˆ ไบŒๅ‰ๆจน +func PreIn2Tree(pre, in []int) *TreeNode { + if len(pre) != len(in) { + panic("preIn2Tree ไธญๅ…ฉๅ€‹ๅˆ‡็‰‡็š„้•ทๅบฆไธ็›ธ็ญ‰") + } + + if len(in) == 0 { + return nil + } + + res := &TreeNode{ + Val: pre[0], + } + + if len(in) == 1 { + return res + } + + idx := indexOf(res.Val, in) + + res.Left = PreIn2Tree(pre[1:idx+1], in[:idx]) + res.Right = PreIn2Tree(pre[idx+1:], in[idx+1:]) + + return res +} + +// InPost2Tree ๆŠŠ inorder ๅ’Œ postorder ๅˆ‡็‰‡่ฝ‰ๆ›ๆˆ ไบŒๅ‰ๆจน +func InPost2Tree(in, post []int) *TreeNode { + if len(post) != len(in) { + panic("inPost2Tree ไธญๅ…ฉๅ€‹ๅˆ‡็‰‡็š„้•ทๅบฆไธ็›ธ็ญ‰") + } + + if len(in) == 0 { + return nil + } + + res := &TreeNode{ + Val: post[len(post)-1], + } + + if len(in) == 1 { + return res + } + + idx := indexOf(res.Val, in) + + res.Left = InPost2Tree(in[:idx], post[:idx]) + res.Right = InPost2Tree(in[idx+1:], post[idx:len(post)-1]) + + return res +} + +// Tree2Preorder ๆŠŠ ไบŒๅ‰ๆจน ่ฝ‰ๆ›ๆˆ preorder ็š„ๅˆ‡็‰‡ +func Tree2Preorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := []int{root.Val} + res = append(res, Tree2Preorder(root.Left)...) + res = append(res, Tree2Preorder(root.Right)...) + + return res +} + +// Tree2Inorder ๆŠŠ ไบŒๅ‰ๆจน ่ฝ‰ๆ›ๆˆ inorder ็š„ๅˆ‡็‰‡ +func Tree2Inorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := Tree2Inorder(root.Left) + res = append(res, root.Val) + res = append(res, Tree2Inorder(root.Right)...) + + return res +} + +// Tree2Postorder ๆŠŠ ไบŒๅ‰ๆจน ่ฝ‰ๆ›ๆˆ postorder ็š„ๅˆ‡็‰‡ +func Tree2Postorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := Tree2Postorder(root.Left) + res = append(res, Tree2Postorder(root.Right)...) + res = append(res, root.Val) + + return res +} + +// Equal return ture if tn == a +func (tn *TreeNode) Equal(a *TreeNode) bool { + if tn == nil && a == nil { + return true + } + + if tn == nil || a == nil || tn.Val != a.Val { + return false + } + + return tn.Left.Equal(a.Left) && tn.Right.Equal(a.Right) +} + +// Tree2ints ๆŠŠ *TreeNode ๆŒ‰็…ง่กŒ้‚„ๅŽŸๆˆ []int +func Tree2ints(tn *TreeNode) []int { + res := make([]int, 0, 1024) + + queue := []*TreeNode{tn} + + for len(queue) > 0 { + size := len(queue) + for i := 0; i < size; i++ { + nd := queue[i] + if nd == nil { + res = append(res, NULL) + } else { + res = append(res, nd.Val) + queue = append(queue, nd.Left, nd.Right) + } + } + queue = queue[size:] + } + + i := len(res) + for i > 0 && res[i-1] == NULL { + i-- + } + + return res[:i] +} + +// T2s convert *TreeNode to []int +func T2s(head *TreeNode, array *[]int) { + fmt.Printf("้‹่กŒๅˆฐ้€™่ฃกไบ† head = %v array = %v\n", head, array) + // fmt.Printf("****array = %v\n", array) + // fmt.Printf("****head = %v\n", head.Val) + *array = append(*array, head.Val) + if head.Left != nil { + T2s(head.Left, array) + } + if head.Right != nil { + T2s(head.Right, array) + } +} + +func BuildTree(nums []int, index int) *TreeNode { + if index >= len(nums) || nums[index] == -1 { + return nil + } + root := &TreeNode{Val: nums[index]} + root.Left = BuildTree(nums, 2*index+1) + root.Right = BuildTree(nums, 2*index+2) + return root +} + +func IntsToTree(nums []int) *TreeNode { + return BuildTree(nums, 0) +} diff --git a/Utility/structures/tree/BinaryTree.go b/Utility/structures/tree/BinaryTree.go new file mode 100644 index 000000000..ae05c3064 --- /dev/null +++ b/Utility/structures/tree/BinaryTree.go @@ -0,0 +1,207 @@ +package tree + +import ( + "fmt" +) + +/* + 0 + / \ + 1 2 + / \ \ + 3 4 5 + / \ / \ +6 7 8 9 +Preorder Traversal ๅ‰ๅบ้ๆญท = Depth-first Search +็†่ซ–ไธŠ็š„้ๆญท้ †ๅบๆ˜ฏ๏ผšๆ นใ€ๅทฆๅญๆจนใ€ๅณๅญๆจนใ€‚ๆ นๆŽ’ๅœจๅ‰้ขใ€‚ +0 1 3 6 7 4 2 5 8 9 + +Inorder Traversal ไธญๅบ้ๆญท +็†่ซ–ไธŠ็š„้ๆญท้ †ๅบๆ˜ฏ๏ผšๅทฆๅญๆจนใ€ๆ นใ€ๅณๅญๆจนใ€‚ๆ นๆŽ’ๅœจไธญ้–“ใ€‚ +ๅฏฆ้š›ไธŠๆ˜ฏๆŽก็”จDepth-first Search๏ผŒๅชไธ้Žๆ›ดๅ‹•ไบ†็ฏ€้ปž็š„่ผธๅ‡บ้ †ๅบใ€‚ +6 3 7 1 4 0 2 8 5 9 + +Postorder Traversal ๅพŒๅบ้ๆญท +็†่ซ–ไธŠ็š„้ๆญท้ †ๅบๆ˜ฏ๏ผšๅทฆๅญๆจนใ€ๅณๅญๆจนใ€ๆ นใ€‚ๆ นๆŽ’ๅœจๅพŒ้ขใ€‚ +ๅฏฆ้š›ไธŠๆ˜ฏๆŽก็”จDepth-first Search๏ผŒๅชไธ้Žๆ›ดๅ‹•ไบ†็ฏ€้ปž็š„่ผธๅ‡บ้ †ๅบใ€‚ +6 7 3 4 1 8 9 5 2 0 + +Level-order Traversal ๅฑคๅบ้ๆญท +ๅณๆ˜ฏBreadth-first Searchใ€‚ +0 1 2 3 4 5 6 7 8 9 +*/ + +type BinaryTree struct { + root *Node +} + +// type Node struct { +// data interface{} +// left *Node +// right *Node +// } + +func NewBinaryTree(rootV interface{}) *BinaryTree { + return &BinaryTree{NewNode(rootV)} +} + +// BFSTraverse: ๅปฃๅบฆๅ„ชๅ…ˆ, Breadth First Traverse ๅปฃๅบฆๅ„ชๅ…ˆ +// ็”จ Queueๅฏฆ็พ +func (this *BinaryTree) BFSTraverse() { + p := this.root + s := NewQueueStack() + + if p == nil { + return + } + s.Push(p) + for !s.IsEmpty() { + node := s.Head().(*Node) + + if node.left != nil { + s.Push(node.left) + } + if node.right != nil { + s.Push(node.right) + } + + tmp := s.Pop().(*Node) + fmt.Printf("%+v ", tmp.data) + } + fmt.Println() +} + +// PreOrderTraverse : ๆทฑๅบฆๅ„ชๅ…ˆ, ๅ‰ๅบ้ๆญท +// ่‹ฅไบŒๅ…ƒๆจน็‚บ็ฉบๅ›žๅ‚ณ็ฉบ, ๅฆๅ‰‡ๅ…ˆๆ น็ฏ€้ปž-> ๅทฆๅญๆจน -> ๅณๅญๆจน +func (this *BinaryTree) PreOrderTraverse() { + p := this.root + s := NewArrayStack() + + for !s.IsEmpty() || nil != p { + if nil != p { + fmt.Printf("%+v ", p.data) + s.Push(p) + p = p.left + } else { + p = s.Pop().(*Node).right + } + } +} + +func (this *Node) PreOrderTraverseRecursive() { + p := this + if p == nil { + return + } + + fmt.Printf("%+v ", p.data) + left := p.left + right := p.right + left.PreOrderTraverseRecursive() + right.PreOrderTraverseRecursive() +} + +// InOrderTraverse : ๆทฑๅบฆๅ„ชๅ…ˆ, ไธญๅบ้ๆญท +// ่‹ฅไบŒๅ…ƒๆจน็‚บ็ฉบๅ›žๅ‚ณ็ฉบ, ๅฆๅ‰‡ๅพžๆ น็ต้ปž้–‹ๅง‹, ๅ…ˆ่ตฐ่จชๆ น็ฏ€้ปž็š„ๅทฆๅญๆจน -> ๆ น็ฏ€้ปž -> ๅณๅญๆจน +func (this *BinaryTree) InOrderTraverse() { + p := this.root + s := NewArrayStack() + + for !s.IsEmpty() || nil != p { + if nil != p { + s.Push(p) + p = p.left + } else { + tmp := s.Pop().(*Node) + fmt.Printf("%+v ", tmp.data) + p = tmp.right + } + } + fmt.Println() +} + +// InOrderTraverseRecursive : ไธญๅบ้ๆญท ้ž่ฟด +func (this *Node) InOrderTraverseRecursive() { + p := this + if p == nil { + return + } + + left := p.left + left.PreOrderTraverseRecursive() + + fmt.Printf("%+v ", p.data) + + right := p.right + right.PreOrderTraverseRecursive() +} + +// PostOrderTraverse : ๆทฑๅบฆๅ„ชๅ…ˆ, ๅพŒๅบ้ๆญท +// ่‹ฅไบŒๅ…ƒๆจน็‚บ็ฉบๅ›žๅ‚ณ็ฉบ, ๅฆๅ‰‡ๅพžๅทฆๅˆฐๅณ่ช’ไธฆๅพž่‘‰ๅญ็ฏ€้ปžๅพŒ็บŒ่ตฐ่จชๅทฆๅญๆจนๅˆฐๅณๅญๆจน, ๆœ€ๅพŒๆ˜ฏๆ‹œ่จชๆ น็ฏ€้ปž +func (this *BinaryTree) PostOrderTraverse() { + s1 := NewArrayStack() + s2 := NewArrayStack() + s1.Push(this.root) + + for !s1.IsEmpty() { + p := s1.Pop().(*Node) + s2.Push(p) + if p.left != nil { + s1.Push(p.left) + } + if p.right != nil { + s1.Push(p.right) + } + } + + for !s2.IsEmpty() { + fmt.Printf("%+v ", s2.Pop().(*Node).data) + } + + fmt.Println() +} + +// PostOrderTraverse2 : ๆทฑๅบฆๅ„ชๅ…ˆ, ๅพŒๅบ้ๆญท +// use one stack, pre cursor to traverse from post order +// ่‹ฅไบŒๅ…ƒๆจน็‚บ็ฉบๅ›žๅ‚ณ็ฉบ, ๅฆๅ‰‡ๅพžๅทฆๅˆฐๅณ่ช’ไธฆๅพž่‘‰ๅญ็ฏ€้ปžๅพŒ็บŒ่ตฐ่จชๅทฆๅญๆจนๅˆฐๅณๅญๆจน, ๆœ€ๅพŒๆ˜ฏๆ‹œ่จชๆ น็ฏ€้ปž +func (this *BinaryTree) PostOrderTraverse2() { + r := this.root + s := NewArrayStack() + + //point to last visit node + var pre *Node + + s.Push(r) + + for !s.IsEmpty() { + r = s.Top().(*Node) + if (r.left == nil && r.right == nil) || (pre != nil && (pre == r.left || pre == r.right)) { + fmt.Printf("%+v ", r.data) + s.Pop() + pre = r + } else { + if r.right != nil { + s.Push(r.right) + } + + if r.left != nil { + s.Push(r.left) + } + } + } + fmt.Println() +} + +// PostOrderTraverseRecursive : ๅพŒๅบ้ๆญท ้ž่ฟด +func (this *Node) PostOrderTraverseRecursive() { + p := this + if p == nil { + return + } + + left := p.left + right := p.right + left.PreOrderTraverseRecursive() + right.PreOrderTraverseRecursive() + fmt.Printf("%+v ", p.data) +} diff --git a/Utility/structures/tree/BinaryTree_test.go b/Utility/structures/tree/BinaryTree_test.go new file mode 100644 index 000000000..2bf9be64f --- /dev/null +++ b/Utility/structures/tree/BinaryTree_test.go @@ -0,0 +1,87 @@ +package tree + +import ( + "testing" +) + +// 1 +// / \ +// 3 4 +// / +// 5 +func TestBinaryTree_BFSTraverse(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + binaryTree.BFSTraverse() // 1 3 4 5 +} + +// ๅ‰ๅบ้ๆญท +func TestBinaryTree_PreOrderTraverse(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + + binaryTree.PreOrderTraverse() //1 3 4 5 +} + +func TestBinaryTree_PreOrderTraverseRecursive(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + + binaryTree.root.PreOrderTraverseRecursive() //1 3 4 5 +} + +//ไธญๅบ้ๆญท +func TestBinaryTree_InOrderTraverse(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + + binaryTree.InOrderTraverse() // 3 1 5 4 +} + +//ไธญๅบ้ๆญท ้ž่ฟด +func TestBinaryTree_InOrderTraverseRecursive(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + + binaryTree.root.InOrderTraverseRecursive() // 3 1 5 4 +} + +//ๅพŒๅบ้ๆญท +func TestBinaryTree_PostOrderTraverse(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + + binaryTree.PostOrderTraverse() // 3 5 4 1 +} + +//ๅพŒๅบ้ๆญท +func TestBinaryTree_PostOrderTraverse2(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + + binaryTree.PostOrderTraverse2() // 3 5 4 1 +} + +//ๅพŒๅบ้ๆญท ้ž่ฟด +func TestBinaryTree_PostOrderTraverseRecursive(t *testing.T) { + binaryTree := NewBinaryTree(1) + binaryTree.root.left = NewNode(3) + binaryTree.root.right = NewNode(4) + binaryTree.root.right.left = NewNode(5) + + binaryTree.root.PostOrderTraverseRecursive() // 3 5 4 1 +} diff --git a/Utility/structures/tree/QueueBasedOnArray.go b/Utility/structures/tree/QueueBasedOnArray.go new file mode 100644 index 000000000..4067d8390 --- /dev/null +++ b/Utility/structures/tree/QueueBasedOnArray.go @@ -0,0 +1,80 @@ +package tree + +import "fmt" + +/* +tree stack +*/ + +type QueueStack struct { + //data + data []interface{} + //stack + top int +} + +func NewQueueStack() *QueueStack { + return &QueueStack{ + data: make([]interface{}, 0, 32), + top: -1, + } +} + +func (this *QueueStack) IsEmpty() bool { + if this.top < 0 { + return true + } + return false +} + +func (this *QueueStack) Push(v interface{}) { + if this.top < 0 { + this.top = 0 + } else { + this.top += 1 + } + + if this.top > len(this.data)-1 { + this.data = append(this.data, v) + } else { + this.data[this.top] = v + } +} + +func (this *QueueStack) Pop() interface{} { + if this.IsEmpty() { + return nil + } + v := this.data[0] + this.data = this.data[1:] + this.top -= 1 + return v +} + +func (this *QueueStack) Head() interface{} { + if this.IsEmpty() { + return nil + } + return this.data[0] +} + +func (this *QueueStack) Top() interface{} { + if this.IsEmpty() { + return nil + } + return this.data[this.top] +} + +func (this *QueueStack) Flush() { + this.top = -1 +} + +func (this *QueueStack) Print() { + if this.IsEmpty() { + fmt.Println("empty statck") + } else { + for i := this.top; i >= 0; i-- { + fmt.Println(this.data[i]) + } + } +} diff --git a/Utility/structures/tree/StackBasedOnArray.go b/Utility/structures/tree/StackBasedOnArray.go new file mode 100644 index 000000000..e24b81570 --- /dev/null +++ b/Utility/structures/tree/StackBasedOnArray.go @@ -0,0 +1,72 @@ +package tree + +import "fmt" + +/* +tree stack +*/ + +type ArrayStack struct { + //data + data []interface{} + //stack + top int +} + +func NewArrayStack() *ArrayStack { + return &ArrayStack{ + data: make([]interface{}, 0, 32), + top: -1, + } +} + +func (this *ArrayStack) IsEmpty() bool { + if this.top < 0 { + return true + } + return false +} + +func (this *ArrayStack) Push(v interface{}) { + if this.top < 0 { + this.top = 0 + } else { + this.top += 1 + } + + if this.top > len(this.data)-1 { + this.data = append(this.data, v) + } else { + this.data[this.top] = v + } +} + +func (this *ArrayStack) Pop() interface{} { + if this.IsEmpty() { + return nil + } + v := this.data[this.top] + this.top -= 1 + return v +} + +func (this *ArrayStack) Top() interface{} { + if this.IsEmpty() { + return nil + } + return this.data[this.top] +} + +func (this *ArrayStack) Flush() { + this.top = -1 +} + +func (this *ArrayStack) Print() { + if this.IsEmpty() { + fmt.Println("empty statck") + } else { + for i := this.top; i >= 0; i-- { + fmt.Println(this.data[i]) + } + } +} diff --git a/Utility/structures/tree/tree.go b/Utility/structures/tree/tree.go new file mode 100644 index 000000000..351a819f4 --- /dev/null +++ b/Utility/structures/tree/tree.go @@ -0,0 +1,27 @@ +package tree + +import "fmt" + +type Node struct { + data interface{} + left *Node + right *Node +} + +func NewNode(data interface{}) *Node { + return &Node{data: data} +} + +func (this *Node) String() string { + return fmt.Sprintf("v:%+v, left:%+v, right:%+v", this.data, this.left, this.right) + // return fmt.Sprintf("v:%+v, left:%+v, right:%+v", this.data, this.left, this.right) +} + +// func main() { +// a := Node{"a", nil, nil} +// b := Node{"b", nil, nil} +// c := Node{"c", nil, nil} +// a.left = &b +// b.right = &c +// fmt.Println(a.String()) +// } diff --git a/assets/images/0046.permutations.png b/assets/images/0046.permutations.png new file mode 100644 index 000000000..943ca25e5 Binary files /dev/null and b/assets/images/0046.permutations.png differ diff --git a/assets/images/0142.LinkedListCycleII.jpg b/assets/images/0142.LinkedListCycleII.jpg new file mode 100644 index 000000000..be0bd9823 Binary files /dev/null and b/assets/images/0142.LinkedListCycleII.jpg differ diff --git a/assets/images/fibfrog.jpg b/assets/images/fibfrog.jpg new file mode 100644 index 000000000..4930c1c9b Binary files /dev/null and b/assets/images/fibfrog.jpg differ diff --git a/gitbook/fonts/fontawesome/FontAwesome.otf b/gitbook/fonts/fontawesome/FontAwesome.otf new file mode 100644 index 000000000..d4de13e83 Binary files /dev/null and b/gitbook/fonts/fontawesome/FontAwesome.otf differ diff --git a/gitbook/fonts/fontawesome/fontawesome-webfont.eot b/gitbook/fonts/fontawesome/fontawesome-webfont.eot new file mode 100644 index 000000000..c7b00d2ba Binary files /dev/null and b/gitbook/fonts/fontawesome/fontawesome-webfont.eot differ diff --git a/gitbook/fonts/fontawesome/fontawesome-webfont.svg b/gitbook/fonts/fontawesome/fontawesome-webfont.svg new file mode 100644 index 000000000..8b66187fe --- /dev/null +++ b/gitbook/fonts/fontawesome/fontawesome-webfont.svg @@ -0,0 +1,685 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/gitbook/fonts/fontawesome/fontawesome-webfont.ttf b/gitbook/fonts/fontawesome/fontawesome-webfont.ttf new file mode 100644 index 000000000..f221e50a2 Binary files /dev/null and b/gitbook/fonts/fontawesome/fontawesome-webfont.ttf differ diff --git a/gitbook/fonts/fontawesome/fontawesome-webfont.woff b/gitbook/fonts/fontawesome/fontawesome-webfont.woff new file mode 100644 index 000000000..6e7483cf6 Binary files /dev/null and b/gitbook/fonts/fontawesome/fontawesome-webfont.woff differ diff --git a/gitbook/fonts/fontawesome/fontawesome-webfont.woff2 b/gitbook/fonts/fontawesome/fontawesome-webfont.woff2 new file mode 100644 index 000000000..7eb74fd12 Binary files /dev/null and b/gitbook/fonts/fontawesome/fontawesome-webfont.woff2 differ diff --git a/gitbook/gitbook-plugin-auto-scroll-table/plugin.js b/gitbook/gitbook-plugin-auto-scroll-table/plugin.js new file mode 100644 index 000000000..b607d9191 --- /dev/null +++ b/gitbook/gitbook-plugin-auto-scroll-table/plugin.js @@ -0,0 +1,10 @@ +(function() { + [].slice.call(document.querySelectorAll('table')).forEach(function(el){ + var wrapper = document.createElement('div'); + wrapper.className = 'table-area'; + el.parentNode.insertBefore(wrapper, el); + el.parentNode.removeChild(el); + wrapper.appendChild(el); + }); + })(); + \ No newline at end of file diff --git a/gitbook/gitbook-plugin-auto-scroll-table/website.css b/gitbook/gitbook-plugin-auto-scroll-table/website.css new file mode 100644 index 000000000..f48a882c0 --- /dev/null +++ b/gitbook/gitbook-plugin-auto-scroll-table/website.css @@ -0,0 +1,40 @@ +table { + width: 100%; /*่กจๆ ผๅฎฝๅบฆ*/ + max-width: 65em; /*่กจๆ ผๆœ€ๅคงๅฎฝๅบฆ๏ผŒ้ฟๅ…่กจๆ ผ่ฟ‡ๅฎฝ*/ + border: 1px solid #dedede; /*่กจๆ ผๅค–่พนๆก†่ฎพ็ฝฎ*/ + margin: 15px auto; /*ๅค–่พน่ท*/ + border-collapse: collapse; /*ไฝฟ็”จๅ•ไธ€็บฟๆก็š„่พนๆก†*/ + empty-cells: show; /*ๅ•ๅ…ƒๆ ผๆ— ๅ†…ๅฎนไพๆ—ง็ป˜ๅˆถ่พนๆก†*/ +} +table th, +table td { + height: 35px; /*็ปŸไธ€ๆฏไธ€่กŒ็š„้ป˜่ฎค้ซ˜ๅบฆ*/ + border: 1px solid #dedede; /*ๅ†…้ƒจ่พนๆก†ๆ ทๅผ*/ + padding: 0 10px; /*ๅ†…่พน่ท*/ +} + +table th { + font-weight: bold; /*ๅŠ ็ฒ—*/ + text-align: center !important; /*ๅ†…ๅฎนๅฑ…ไธญ๏ผŒๅŠ ไธŠ !important ้ฟๅ…่ขซ Markdown ๆ ทๅผ่ฆ†็›–*/ + background: rgba(158,188,226,0.2); /*่ƒŒๆ™ฏ่‰ฒ*/ +} + +table tbody tr:nth-child(2n) { + background: rgba(158,188,226,0.12); +} + +table tr:hover { + background: #efefef; +} + +table th { + white-space: nowrap; /*่กจๅคดๅ†…ๅฎนๅผบๅˆถๅœจไธ€่กŒๆ˜พ็คบ*/ +} + +table td:nth-child(1) { + white-space: nowrap; +} + +.table-area { + overflow: auto; +} \ No newline at end of file diff --git a/gitbook/gitbook-plugin-back-to-top-button/plugin.css b/gitbook/gitbook-plugin-back-to-top-button/plugin.css new file mode 100644 index 000000000..a418cbb57 --- /dev/null +++ b/gitbook/gitbook-plugin-back-to-top-button/plugin.css @@ -0,0 +1,55 @@ +.back-to-top { + position: fixed; + bottom: 25px; + right: 25px; + background: rgba(0, 0, 0, 0.5); + width: 50px; + height: 50px; + display: block; + text-decoration: none; + -webkit-border-radius: 35px; + -moz-border-radius: 35px; + border-radius: 35px; + display: none; +} +.back-to-top i { + color: #fff; + margin: 0; + position: relative; + left: 15px; + top: 14px; + font-size: 22px; +} +.back-to-top:hover { + background: rgba(0, 0, 0, 0.9); + cursor: pointer; +} +.book.color-theme-1 .back-to-top { + background: rgba(112, 66, 20, 0.5); +} +.book.color-theme-1 .back-to-top i { + color: #f3eacb; +} +.book.color-theme-1 .back-to-top:hover { + background: rgba(112, 66, 20, 0.9); +} +.book.color-theme-2 .back-to-top { + background: rgba(189, 202, 219, 0.5); +} +.book.color-theme-2 .back-to-top i { + color: #1C1F2B; +} +.book.color-theme-2 .back-to-top:hover { + background: rgba(189, 202, 219, 0.9); +} + +@media only screen + and (min-device-width: 320px) + and (max-device-width: 480px) + and (-webkit-min-device-pixel-ratio: 2) + and (orientation: portrait) { + .back-to-top { + bottom: 10px; + right: 10px; + } +} \ No newline at end of file diff --git a/gitbook/gitbook-plugin-back-to-top-button/plugin.js b/gitbook/gitbook-plugin-back-to-top-button/plugin.js new file mode 100644 index 000000000..abd35237d --- /dev/null +++ b/gitbook/gitbook-plugin-back-to-top-button/plugin.js @@ -0,0 +1,25 @@ +var gitbook = window.gitbook; + +gitbook.events.on('page.change', function() { + + var back_to_top_button = ['
                                                                                                                                                                                                                                              '].join(""); + $(".book").append(back_to_top_button) + + $(".back-to-top").hide(); + + $('.book-body,.body-inner').on('scroll', function () { + if ($(this).scrollTop() > 100) { + $('.back-to-top').fadeIn(); + } else { + $('.back-to-top').fadeOut(); + } + }); + + $('.back-to-top').click(function () { + $('.book-body,.body-inner').animate({ + scrollTop: 0 + }, 800); + return false; + }); + +}); diff --git a/gitbook/gitbook-plugin-code/plugin.css b/gitbook/gitbook-plugin-code/plugin.css new file mode 100644 index 000000000..a68fcdc00 --- /dev/null +++ b/gitbook/gitbook-plugin-code/plugin.css @@ -0,0 +1,37 @@ +#code-textarea { + height: 0; + position: fixed; + top: -1000px; + width: 0; +} + +.code-wrapper { + position: relative; +} + +.code-wrapper i { + color: #c1c7cd; + cursor: pointer; + font-size: 12px; + font-weight: bold; + position: absolute; + right: 1em; + top: 1em; +} + +.code-wrapper pre { + background: #f7f8f9; + border-radius: 3px; + counter-reset: line; + font-size: 15px; +} + +.code-wrapper pre > code > span.code-line:before { + counter-increment: line; + color: #c1c7cd; + content: counter(line); + display: inline-block; + font-size: 12px; + margin-right: 1.5em; + width: 1em; +} diff --git a/gitbook/gitbook-plugin-code/plugin.js b/gitbook/gitbook-plugin-code/plugin.js new file mode 100644 index 000000000..555d72467 --- /dev/null +++ b/gitbook/gitbook-plugin-code/plugin.js @@ -0,0 +1,91 @@ +require(['gitbook', 'jQuery'], function(gitbook, $) { + + const TERMINAL_HOOK = '**[terminal]' + + var pluginConfig = {}; + var timeouts = {}; + + function addCopyButton(wrapper) { + wrapper.append( + $('') + .click(function() { + copyCommand($(this)); + }) + ); + } + + function addCopyTextarea() { + + /* Add also the text area that will allow to copy */ + $('body').append('",pe.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue}();var Qe=te.documentElement,Je=/^key/,Ke=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Ze=/^([^.]*)(?:\.(.+)|)/;de.event={global:{},add:function(e,t,n,r,o){var i,s,a,u,c,l,f,p,h,d,g,m=Fe.get(e);if(m)for(n.handler&&(i=n,n=i.handler,o=i.selector),o&&de.find.matchesSelector(Qe,o),n.guid||(n.guid=de.guid++),(u=m.events)||(u=m.events={}),(s=m.handle)||(s=m.handle=function(t){return"undefined"!=typeof de&&de.event.triggered!==t.type?de.event.dispatch.apply(e,arguments):void 0}),t=(t||"").match(qe)||[""],c=t.length;c--;)a=Ze.exec(t[c])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h&&(f=de.event.special[h]||{},h=(o?f.delegateType:f.bindType)||h,f=de.event.special[h]||{},l=de.extend({type:h,origType:g,data:r,handler:n,guid:n.guid,selector:o,needsContext:o&&de.expr.match.needsContext.test(o),namespace:d.join(".")},i),(p=u[h])||(p=u[h]=[],p.delegateCount=0,f.setup&&f.setup.call(e,r,d,s)!==!1||e.addEventListener&&e.addEventListener(h,s)),f.add&&(f.add.call(e,l),l.handler.guid||(l.handler.guid=n.guid)),o?p.splice(p.delegateCount++,0,l):p.push(l),de.event.global[h]=!0)},remove:function(e,t,n,r,o){var i,s,a,u,c,l,f,p,h,d,g,m=Fe.hasData(e)&&Fe.get(e);if(m&&(u=m.events)){for(t=(t||"").match(qe)||[""],c=t.length;c--;)if(a=Ze.exec(t[c])||[],h=g=a[1],d=(a[2]||"").split(".").sort(),h){for(f=de.event.special[h]||{},h=(r?f.delegateType:f.bindType)||h,p=u[h]||[],a=a[2]&&new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),s=i=p.length;i--;)l=p[i],!o&&g!==l.origType||n&&n.guid!==l.guid||a&&!a.test(l.namespace)||r&&r!==l.selector&&("**"!==r||!l.selector)||(p.splice(i,1),l.selector&&p.delegateCount--,f.remove&&f.remove.call(e,l));s&&!p.length&&(f.teardown&&f.teardown.call(e,d,m.handle)!==!1||de.removeEvent(e,h,m.handle),delete u[h])}else for(h in u)de.event.remove(e,h+t[c],n,r,!0);de.isEmptyObject(u)&&Fe.remove(e,"handle events")}},dispatch:function(e){var t,n,r,o,i,s,a=de.event.fix(e),u=new Array(arguments.length),c=(Fe.get(this,"events")||{})[a.type]||[],l=de.event.special[a.type]||{};for(u[0]=a,t=1;t=1))for(;c!==this;c=c.parentNode||this)if(1===c.nodeType&&("click"!==e.type||c.disabled!==!0)){for(i=[],s={},n=0;n-1:de.find(o,this,null,[c]).length),s[o]&&i.push(r);i.length&&a.push({elem:c,handlers:i})}return c=this,u\x20\t\r\n\f]*)[^>]*)\/>/gi,tt=/\s*$/g;de.extend({htmlPrefilter:function(e){return e.replace(et,"<$1>")},clone:function(e,t,n){var r,o,i,s,a=e.cloneNode(!0),u=de.contains(e.ownerDocument,e);if(!(pe.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||de.isXMLDoc(e)))for(s=v(a),i=v(e),r=0,o=i.length;r0&&y(s,!u&&v(e,"script")),a},cleanData:function(e){for(var t,n,r,o=de.event.special,i=0;void 0!==(n=e[i]);i++)if(He(n)){if(t=n[Fe.expando]){if(t.events)for(r in t.events)o[r]?de.event.remove(n,r):de.removeEvent(n,r,t.handle);n[Fe.expando]=void 0}n[Re.expando]&&(n[Re.expando]=void 0)}}}),de.fn.extend({detach:function(e){return q(this,e,!0)},remove:function(e){return q(this,e)},text:function(e){return Le(this,function(e){return void 0===e?de.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return A(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=j(this,e);t.appendChild(e)}})},prepend:function(){return A(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=j(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return A(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return A(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(de.cleanData(v(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return de.clone(this,e,t)})},html:function(e){return Le(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!tt.test(e)&&!Ge[(Xe.exec(e)||["",""])[1].toLowerCase()]){e=de.htmlPrefilter(e);try{for(;n1)}}),de.Tween=I,I.prototype={constructor:I,init:function(e,t,n,r,o,i){this.elem=e,this.prop=n,this.easing=o||de.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=i||(de.cssNumber[n]?"":"px")},cur:function(){var e=I.propHooks[this.prop];return e&&e.get?e.get(this):I.propHooks._default.get(this)},run:function(e){var t,n=I.propHooks[this.prop];return this.options.duration?this.pos=t=de.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):I.propHooks._default.set(this),this}},I.prototype.init.prototype=I.prototype,I.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=de.css(e.elem,e.prop,""),t&&"auto"!==t?t:0)},set:function(e){de.fx.step[e.prop]?de.fx.step[e.prop](e):1!==e.elem.nodeType||null==e.elem.style[de.cssProps[e.prop]]&&!de.cssHooks[e.prop]?e.elem[e.prop]=e.now:de.style(e.elem,e.prop,e.now+e.unit)}}},I.propHooks.scrollTop=I.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},de.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},de.fx=I.prototype.init,de.fx.step={};var ht,dt,gt=/^(?:toggle|show|hide)$/,mt=/queueHooks$/;de.Animation=de.extend(U,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return d(n.elem,e,$e.exec(t),n),n}]},tweener:function(e,t){de.isFunction(e)?(t=e,e=["*"]):e=e.match(qe);for(var n,r=0,o=e.length;r1)},removeAttr:function(e){return this.each(function(){de.removeAttr(this,e)})}}),de.extend({attr:function(e,t,n){var r,o,i=e.nodeType;if(3!==i&&8!==i&&2!==i)return"undefined"==typeof e.getAttribute?de.prop(e,t,n):(1===i&&de.isXMLDoc(e)||(o=de.attrHooks[t.toLowerCase()]||(de.expr.match.bool.test(t)?vt:void 0)),void 0!==n?null===n?void de.removeAttr(e,t):o&&"set"in o&&void 0!==(r=o.set(e,n,t))?r:(e.setAttribute(t,n+""),n):o&&"get"in o&&null!==(r=o.get(e,t))?r:(r=de.find.attr(e,t),null==r?void 0:r))},attrHooks:{type:{set:function(e,t){if(!pe.radioValue&&"radio"===t&&de.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,o=t&&t.match(qe);if(o&&1===e.nodeType)for(;n=o[r++];)e.removeAttribute(n)}}),vt={set:function(e,t,n){return t===!1?de.removeAttr(e,n):e.setAttribute(n,n),n}},de.each(de.expr.match.bool.source.match(/\w+/g),function(e,t){var n=yt[t]||de.find.attr;yt[t]=function(e,t,r){var o,i,s=t.toLowerCase();return r||(i=yt[s],yt[s]=o,o=null!=n(e,t,r)?s:null,yt[s]=i),o}});var xt=/^(?:input|select|textarea|button)$/i,bt=/^(?:a|area)$/i;de.fn.extend({prop:function(e,t){return Le(this,de.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[de.propFix[e]||e]})}}),de.extend({prop:function(e,t,n){var r,o,i=e.nodeType;if(3!==i&&8!==i&&2!==i)return 1===i&&de.isXMLDoc(e)||(t=de.propFix[t]||t,o=de.propHooks[t]),void 0!==n?o&&"set"in o&&void 0!==(r=o.set(e,n,t))?r:e[t]=n:o&&"get"in o&&null!==(r=o.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=de.find.attr(e,"tabindex");return t?parseInt(t,10):xt.test(e.nodeName)||bt.test(e.nodeName)&&e.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),pe.optSelected||(de.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),de.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){de.propFix[this.toLowerCase()]=this}),de.fn.extend({addClass:function(e){var t,n,r,o,i,s,a,u=0;if(de.isFunction(e))return this.each(function(t){de(this).addClass(e.call(this,t,X(this)))});if("string"==typeof e&&e)for(t=e.match(qe)||[];n=this[u++];)if(o=X(n),r=1===n.nodeType&&" "+z(o)+" "){for(s=0;i=t[s++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=z(r),o!==a&&n.setAttribute("class",a)}return this},removeClass:function(e){var t,n,r,o,i,s,a,u=0;if(de.isFunction(e))return this.each(function(t){de(this).removeClass(e.call(this,t,X(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof e&&e)for(t=e.match(qe)||[];n=this[u++];)if(o=X(n),r=1===n.nodeType&&" "+z(o)+" "){for(s=0;i=t[s++];)for(;r.indexOf(" "+i+" ")>-1;)r=r.replace(" "+i+" "," ");a=z(r),o!==a&&n.setAttribute("class",a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):de.isFunction(e)?this.each(function(n){de(this).toggleClass(e.call(this,n,X(this),t),t)}):this.each(function(){var t,r,o,i;if("string"===n)for(r=0,o=de(this),i=e.match(qe)||[];t=i[r++];)o.hasClass(t)?o.removeClass(t):o.addClass(t);else void 0!==e&&"boolean"!==n||(t=X(this),t&&Fe.set(this,"__className__",t),this.setAttribute&&this.setAttribute("class",t||e===!1?"":Fe.get(this,"__className__")||""))})},hasClass:function(e){var t,n,r=0;for(t=" "+e+" ";n=this[r++];)if(1===n.nodeType&&(" "+z(X(n))+" ").indexOf(t)>-1)return!0;return!1}});var wt=/\r/g;de.fn.extend({val:function(e){var t,n,r,o=this[0];{if(arguments.length)return r=de.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=r?e.call(this,n,de(this).val()):e,null==o?o="":"number"==typeof o?o+="":de.isArray(o)&&(o=de.map(o,function(e){return null==e?"":e+""})),t=de.valHooks[this.type]||de.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,o,"value")||(this.value=o))});if(o)return t=de.valHooks[o.type]||de.valHooks[o.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(o,"value"))?n:(n=o.value,"string"==typeof n?n.replace(wt,""):null==n?"":n)}}}),de.extend({valHooks:{option:{get:function(e){var t=de.find.attr(e,"value");return null!=t?t:z(de.text(e))}},select:{get:function(e){var t,n,r,o=e.options,i=e.selectedIndex,s="select-one"===e.type,a=s?null:[],u=s?i+1:o.length;for(r=i<0?u:s?i:0;r-1)&&(n=!0);return n||(e.selectedIndex=-1),i}}}}),de.each(["radio","checkbox"],function(){de.valHooks[this]={set:function(e,t){if(de.isArray(t))return e.checked=de.inArray(de(e).val(),t)>-1}},pe.checkOn||(de.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Tt=/^(?:focusinfocus|focusoutblur)$/;de.extend(de.event,{trigger:function(t,n,r,o){var i,s,a,u,c,l,f,p=[r||te],h=ce.call(t,"type")?t.type:t,d=ce.call(t,"namespace")?t.namespace.split("."):[];if(s=a=r=r||te,3!==r.nodeType&&8!==r.nodeType&&!Tt.test(h+de.event.triggered)&&(h.indexOf(".")>-1&&(d=h.split("."),h=d.shift(),d.sort()),c=h.indexOf(":")<0&&"on"+h,t=t[de.expando]?t:new de.Event(h,"object"==typeof t&&t),t.isTrigger=o?2:3,t.namespace=d.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:de.makeArray(n,[t]),f=de.event.special[h]||{},o||!f.trigger||f.trigger.apply(r,n)!==!1)){if(!o&&!f.noBubble&&!de.isWindow(r)){for(u=f.delegateType||h,Tt.test(u+h)||(s=s.parentNode);s;s=s.parentNode)p.push(s),a=s;a===(r.ownerDocument||te)&&p.push(a.defaultView||a.parentWindow||e)}for(i=0;(s=p[i++])&&!t.isPropagationStopped();)t.type=i>1?u:f.bindType||h,l=(Fe.get(s,"events")||{})[t.type]&&Fe.get(s,"handle"),l&&l.apply(s,n),l=c&&s[c],l&&l.apply&&He(s)&&(t.result=l.apply(s,n),t.result===!1&&t.preventDefault());return t.type=h,o||t.isDefaultPrevented()||f._default&&f._default.apply(p.pop(),n)!==!1||!He(r)||c&&de.isFunction(r[h])&&!de.isWindow(r)&&(a=r[c],a&&(r[c]=null),de.event.triggered=h,r[h](),de.event.triggered=void 0,a&&(r[c]=a)),t.result}},simulate:function(e,t,n){var r=de.extend(new de.Event,n,{type:e,isSimulated:!0});de.event.trigger(r,null,t)}}),de.fn.extend({trigger:function(e,t){return this.each(function(){de.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return de.event.trigger(e,t,n,!0)}}),de.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,t){de.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),de.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),pe.focusin="onfocusin"in e,pe.focusin||de.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){de.event.simulate(t,e.target,de.event.fix(e))};de.event.special[t]={setup:function(){var r=this.ownerDocument||this,o=Fe.access(r,t);o||r.addEventListener(e,n,!0),Fe.access(r,t,(o||0)+1)},teardown:function(){var r=this.ownerDocument||this,o=Fe.access(r,t)-1;o?Fe.access(r,t,o):(r.removeEventListener(e,n,!0),Fe.remove(r,t))}}});var Ct=e.location,jt=de.now(),kt=/\?/;de.parseXML=function(t){var n;if(!t||"string"!=typeof t)return null;try{n=(new e.DOMParser).parseFromString(t,"text/xml")}catch(e){n=void 0}return n&&!n.getElementsByTagName("parsererror").length||de.error("Invalid XML: "+t),n};var Et=/\[\]$/,St=/\r?\n/g,Nt=/^(?:submit|button|image|reset|file)$/i,At=/^(?:input|select|textarea|keygen)/i;de.param=function(e,t){var n,r=[],o=function(e,t){var n=de.isFunction(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(de.isArray(e)||e.jquery&&!de.isPlainObject(e))de.each(e,function(){o(this.name,this.value)});else for(n in e)V(n,e[n],t,o);return r.join("&")},de.fn.extend({serialize:function(){return de.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=de.prop(this,"elements");return e?de.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!de(this).is(":disabled")&&At.test(this.nodeName)&&!Nt.test(e)&&(this.checked||!ze.test(e))}).map(function(e,t){var n=de(this).val();return null==n?null:de.isArray(n)?de.map(n,function(e){return{name:t.name,value:e.replace(St,"\r\n")}}):{name:t.name,value:n.replace(St,"\r\n")}}).get()}});var qt=/%20/g,Dt=/#.*$/,Ot=/([?&])_=[^&]*/,Lt=/^(.*?):[ \t]*([^\r\n]*)$/gm,Ht=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Ft=/^(?:GET|HEAD)$/,Rt=/^\/\//,It={},Pt={},Mt="*/".concat("*"),$t=te.createElement("a");$t.href=Ct.href,de.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ct.href,type:"GET",isLocal:Ht.test(Ct.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Mt,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":de.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Q(Q(e,de.ajaxSettings),t):Q(de.ajaxSettings,e)},ajaxPrefilter:G(It),ajaxTransport:G(Pt),ajax:function(t,n){function r(t,n,r,a){var c,p,h,b,w,T=n;l||(l=!0,u&&e.clearTimeout(u),o=void 0,s=a||"",C.readyState=t>0?4:0,c=t>=200&&t<300||304===t,r&&(b=J(d,C,r)),b=K(d,b,C,c),c?(d.ifModified&&(w=C.getResponseHeader("Last-Modified"),w&&(de.lastModified[i]=w),w=C.getResponseHeader("etag"),w&&(de.etag[i]=w)),204===t||"HEAD"===d.type?T="nocontent":304===t?T="notmodified":(T=b.state,p=b.data,h=b.error,c=!h)):(h=T,!t&&T||(T="error",t<0&&(t=0))),C.status=t,C.statusText=(n||T)+"",c?v.resolveWith(g,[p,T,C]):v.rejectWith(g,[C,T,h]),C.statusCode(x),x=void 0,f&&m.trigger(c?"ajaxSuccess":"ajaxError",[C,d,c?p:h]),y.fireWith(g,[C,T]),f&&(m.trigger("ajaxComplete",[C,d]),--de.active||de.event.trigger("ajaxStop")))}"object"==typeof t&&(n=t,t=void 0),n=n||{};var o,i,s,a,u,c,l,f,p,h,d=de.ajaxSetup({},n),g=d.context||d,m=d.context&&(g.nodeType||g.jquery)?de(g):de.event,v=de.Deferred(),y=de.Callbacks("once memory"),x=d.statusCode||{},b={},w={},T="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(l){if(!a)for(a={};t=Lt.exec(s);)a[t[1].toLowerCase()]=t[2];t=a[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return l?s:null},setRequestHeader:function(e,t){return null==l&&(e=w[e.toLowerCase()]=w[e.toLowerCase()]||e,b[e]=t),this},overrideMimeType:function(e){return null==l&&(d.mimeType=e),this},statusCode:function(e){var t;if(e)if(l)C.always(e[C.status]);else for(t in e)x[t]=[x[t],e[t]];return this},abort:function(e){var t=e||T;return o&&o.abort(t),r(0,t),this}};if(v.promise(C),d.url=((t||d.url||Ct.href)+"").replace(Rt,Ct.protocol+"//"),d.type=n.method||n.type||d.method||d.type,d.dataTypes=(d.dataType||"*").toLowerCase().match(qe)||[""],null==d.crossDomain){c=te.createElement("a");try{c.href=d.url,c.href=c.href,d.crossDomain=$t.protocol+"//"+$t.host!=c.protocol+"//"+c.host}catch(e){d.crossDomain=!0}}if(d.data&&d.processData&&"string"!=typeof d.data&&(d.data=de.param(d.data,d.traditional)),Y(It,d,n,C),l)return C;f=de.event&&d.global,f&&0===de.active++&&de.event.trigger("ajaxStart"),d.type=d.type.toUpperCase(),d.hasContent=!Ft.test(d.type),i=d.url.replace(Dt,""),d.hasContent?d.data&&d.processData&&0===(d.contentType||"").indexOf("application/x-www-form-urlencoded")&&(d.data=d.data.replace(qt,"+")):(h=d.url.slice(i.length),d.data&&(i+=(kt.test(i)?"&":"?")+d.data,delete d.data),d.cache===!1&&(i=i.replace(Ot,"$1"),h=(kt.test(i)?"&":"?")+"_="+jt++ +h),d.url=i+h),d.ifModified&&(de.lastModified[i]&&C.setRequestHeader("If-Modified-Since",de.lastModified[i]),de.etag[i]&&C.setRequestHeader("If-None-Match",de.etag[i])),(d.data&&d.hasContent&&d.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",d.contentType),C.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+Mt+"; q=0.01":""):d.accepts["*"]);for(p in d.headers)C.setRequestHeader(p,d.headers[p]);if(d.beforeSend&&(d.beforeSend.call(g,C,d)===!1||l))return C.abort();if(T="abort",y.add(d.complete),C.done(d.success),C.fail(d.error),o=Y(Pt,d,n,C)){if(C.readyState=1,f&&m.trigger("ajaxSend",[C,d]),l)return C;d.async&&d.timeout>0&&(u=e.setTimeout(function(){C.abort("timeout")},d.timeout));try{l=!1,o.send(b,r)}catch(e){if(l)throw e;r(-1,e)}}else r(-1,"No Transport");return C},getJSON:function(e,t,n){return de.get(e,t,n,"json")},getScript:function(e,t){return de.get(e,void 0,t,"script")}}),de.each(["get","post"],function(e,t){de[t]=function(e,n,r,o){return de.isFunction(n)&&(o=o||r,r=n,n=void 0),de.ajax(de.extend({url:e,type:t,dataType:o,data:n,success:r},de.isPlainObject(e)&&e))}}),de._evalUrl=function(e){return de.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,throws:!0})},de.fn.extend({wrapAll:function(e){var t;return this[0]&&(de.isFunction(e)&&(e=e.call(this[0])),t=de(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstElementChild;)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(e){return de.isFunction(e)?this.each(function(t){de(this).wrapInner(e.call(this,t))}):this.each(function(){var t=de(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=de.isFunction(e);return this.each(function(n){de(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(e){return this.parent(e).not("body").each(function(){de(this).replaceWith(this.childNodes)}),this}}),de.expr.pseudos.hidden=function(e){return!de.expr.pseudos.visible(e)},de.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},de.ajaxSettings.xhr=function(){try{return new e.XMLHttpRequest}catch(e){}};var Wt={0:200,1223:204},Bt=de.ajaxSettings.xhr();pe.cors=!!Bt&&"withCredentials"in Bt,pe.ajax=Bt=!!Bt,de.ajaxTransport(function(t){var n,r;if(pe.cors||Bt&&!t.crossDomain)return{send:function(o,i){var s,a=t.xhr();if(a.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(s in t.xhrFields)a[s]=t.xhrFields[s];t.mimeType&&a.overrideMimeType&&a.overrideMimeType(t.mimeType),t.crossDomain||o["X-Requested-With"]||(o["X-Requested-With"]="XMLHttpRequest");for(s in o)a.setRequestHeader(s,o[s]);n=function(e){return function(){n&&(n=r=a.onload=a.onerror=a.onabort=a.onreadystatechange=null,"abort"===e?a.abort():"error"===e?"number"!=typeof a.status?i(0,"error"):i(a.status,a.statusText):i(Wt[a.status]||a.status,a.statusText,"text"!==(a.responseType||"text")||"string"!=typeof a.responseText?{binary:a.response}:{text:a.responseText},a.getAllResponseHeaders()))}},a.onload=n(),r=a.onerror=n("error"),void 0!==a.onabort?a.onabort=r:a.onreadystatechange=function(){4===a.readyState&&e.setTimeout(function(){n&&r()})},n=n("abort");try{a.send(t.hasContent&&t.data||null)}catch(e){if(n)throw e}},abort:function(){n&&n()}}}),de.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),de.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return de.globalEval(e),e}}}),de.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),de.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(r,o){t=de(" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              + + + + + + + + +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                                              Leetcode in Golang

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Build latest tag Build my gitbook and deploy to gh-pages pages-build-deployment

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Leetcode, Codility , GeekforGeeks algorithms exercises written in Golang.

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              https://kimi0230.github.io/LeetcodeGolang/

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              leetcode Content

                                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                                              Data Structure

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Array & String

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0001Two SumGoEasyO(n)O(n)Array
                                                                                                                                                                                                                                              0003Longest Substring Without Repeating CharactersGoMediumO(n)O(1)Array, Sliding Window
                                                                                                                                                                                                                                              00153 SumGoMediumO(n^2)O(n)Array
                                                                                                                                                                                                                                              0027Remove ElementGoEasyO(n)O(1)Array
                                                                                                                                                                                                                                              0035Search Insert PositionGoEasyO(n), O(logn)O(1)Array
                                                                                                                                                                                                                                              0049Search Insert PositionGoMediumO(kn)O(kn)Array
                                                                                                                                                                                                                                              0059Spiral Matrix IIGoMediumO(n)O(n^2)Array
                                                                                                                                                                                                                                              0088Merge Sorted ArrayGoEasyO(n)O(1)Array
                                                                                                                                                                                                                                              02170217.Contains DuplicateGoEasyO(n)O(n)Array
                                                                                                                                                                                                                                              02420242.Valid AnagramGoEasyO(n)O(n)Array
                                                                                                                                                                                                                                              0409409. Longest PalindromeGoEasyO(n)O(1)Array
                                                                                                                                                                                                                                              03800380.Insert Delete GetRandom O(1)GoMediumO(1)O(n)Array
                                                                                                                                                                                                                                              03810381.Insert Delete GetRandom O(1) Duplicates allowedGoMediumO(1)O(n)Array
                                                                                                                                                                                                                                              04120412.Fizz BuzzGoEasyO(n)O(n)Array, string
                                                                                                                                                                                                                                              11951195.Fizz Buzz MultithreadedGoMediumO(n)Array, string,Concurrency
                                                                                                                                                                                                                                              0238238. Product of Array Except SelfGoMediumO(n)Array, string, Prefix Sum
                                                                                                                                                                                                                                              0128128. Longest Consecutive SequenceGoMediumO(n)O(n)Array, Hash Table, Union Find
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Matrix

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Linked List

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0019Remove Nth Node From End of ListGoMediumO(n)O(1)Linked List, Two Pointers
                                                                                                                                                                                                                                              0141Linked List CycleGoEasyO(n)O(1)Linked List, Two Pointers
                                                                                                                                                                                                                                              0142Linked List Cycle IIGoMediumO(n)O(1)Linked List, Two Pointers
                                                                                                                                                                                                                                              0203Remove Linked List ElementsGoEasyO(n)O(1)Linked List
                                                                                                                                                                                                                                              0206Reverse Linked ListGoEasyO(n)O(1)Linked List
                                                                                                                                                                                                                                              0876Middle of the Linked ListGoEasyLinked List, Two Pointers
                                                                                                                                                                                                                                              0021Merge Two Sorted ListsGoEasyO(log n)O(1)Linked List
                                                                                                                                                                                                                                              0002Add Two NumberGoMediumO(max(m,n))O(1)Linked List
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              HashSet & HashMap

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Stack & Queue

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0020Valid ParenthesesGoEasyO(n)O(n)Stack
                                                                                                                                                                                                                                              0094Binary Tree Inorder TraversalGoMediumO(n)O(1)Stack
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Heap & Priority Queue

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Heap 總是能讓整棵樹當中最大或最小值維持在root節點上

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Heap 有幾個特色:
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                              • 常見架構是像 binary tree 那樣
                                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                                              • 保持 balanced
                                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                                              • max heap 的 root 是最大值;min heap 的 root 則是最小值
                                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                                              • 雖然是 tree,卻很適合放在 array 中處理
                                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              heap sort
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              根據定義 heap 的 root 一定是最大(假設是 max heap),也就是說,無序數列經過 heapify 再作 n 次 root deletion 取出最大值,就可以得到排序的結果。 +最後就得到 heap sort 的 worst case 時間複雜度 O(nlogn) 的結果。 +可是 quick sort 的 worst case 時間複雜度是 O(n²),怎麼 quick sort 的時間複雜度比較糟糕卻比較受歡迎? +google 的結果是說 heap sort 比較不利於 caching 對於 spatial locality 機制,蠻有道理的阿。

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0703Kth Largest Element in a StreamGoEasyO(K + (N-K)logK)O(k)Heap, Priority Queue
                                                                                                                                                                                                                                              1046Last Stone WeightGoEasyO(nlogn)O(n)Heap, Priority Queue
                                                                                                                                                                                                                                              0347Top K Frequent ElementsGoMediumO(Nlog⁡k)O(n)Heap, Priority Queue, Quick Sort
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Disjoint Set Union

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Trie

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Binary Indexed Tree

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Design Data Structures

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Algorithm

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Greedy

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Sort

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0075Sort ColorsGoMediumO(n)O(1)Sort
                                                                                                                                                                                                                                              0215Kth Largest Element in an ArrayGoMediumO(n)O(logn)Sort
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Multiple Pointers

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Backtracking (回溯法). DFS

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              DFS. 解決一個回溯問題, 實際上就是一個決策樹的遍歷過程. +算是一個暴力的窮舉算法

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                              1. 路徑:也就是已經做出的選擇。
                                                                                                                                                                                                                                              2. +
                                                                                                                                                                                                                                              3. 選擇列表:也就是你當前可以做的選擇。
                                                                                                                                                                                                                                              4. +
                                                                                                                                                                                                                                              5. 結束條件:也就是到達決策樹底層,無法再做選擇的條件。
                                                                                                                                                                                                                                              6. +
                                                                                                                                                                                                                                              7. https://www.bilibili.com/video/BV1P5411N7Xc
                                                                                                                                                                                                                                              8. +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              result = []
                                                                                                                                                                                                                                              +def backtrack(路徑, 選擇列表):
                                                                                                                                                                                                                                              +    if 滿足結束條件:
                                                                                                                                                                                                                                              +        result.add(路徑)
                                                                                                                                                                                                                                              +        return
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +    for 選擇 in 選擇列表:
                                                                                                                                                                                                                                              +        做選擇(前序)
                                                                                                                                                                                                                                              +        backtrack(路徑, 選擇列表)
                                                                                                                                                                                                                                              +        撤銷選擇(後序)
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0046Permutations (全排列)GoMediumO(n)O(n)Backtracking
                                                                                                                                                                                                                                              0078SubsetsGoMediumO(n^2)O(n)Backtracking
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              DFS & BFS

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              找最短路徑用BFS, +其他時用DFS用得多一些, 因為遞迴較好寫

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              假設有棵滿的二叉樹,節點數為 N. 對DFS來說空間複雜度就是遞迴, 最壞的情況就是樹的高度 O(log N) +BFS算法, Queue每次都會存二叉樹一層的節點, 最壞的情況下空間複雜度應該就是樹的最下層的數量, 也就是 N/2. 空間複雜度 O(N)

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              DFS(深度優先搜索)通常使用堆棧(Stack)來實現。在DFS中,您首先處理一個節點,然後將其子節點按某種順序推入堆棧中,接著繼續處理堆棧頂部的節點,直到堆棧為空。 +BFS(廣度優先搜索)則使用隊列(Queue)來實現。在BFS中,您首先處理一個節點,然後將其子節點按某種順序排隊,接著繼續處理隊列的前端節點,直到隊列為空。

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0695Max Area of IslandGoMediumO(m*n)O(m*n)DFS & BFS
                                                                                                                                                                                                                                              0733Flood FillGoEasyO(m*n)O(m*n)DFS & BFS
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Dynamic Programming

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              動態規劃問題的一般形式就是求最值, 最長遞增子序列, 最小編輯距離等. 核心問題是窮舉

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                              1. 重疊子問題
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                1. memory table
                                                                                                                                                                                                                                                2. +
                                                                                                                                                                                                                                                3. DP table
                                                                                                                                                                                                                                                4. +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                              2. +
                                                                                                                                                                                                                                              3. 最優子結構
                                                                                                                                                                                                                                              4. +
                                                                                                                                                                                                                                              5. 狀態轉移方程式
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                1. 這問題的 base case (最簡單情況) 是什麼?
                                                                                                                                                                                                                                                2. +
                                                                                                                                                                                                                                                3. 這問題有什麼狀態
                                                                                                                                                                                                                                                4. +
                                                                                                                                                                                                                                                5. 對於每個狀態, 可以做出什麼選擇, 使得狀態發生改變
                                                                                                                                                                                                                                                6. +
                                                                                                                                                                                                                                                7. 如何定義 dp 數組/函數的含義來表現狀態選擇?
                                                                                                                                                                                                                                                8. +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                              6. +
                                                                                                                                                                                                                                              + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              替換 /跳過
                                                                                                                                                                                                                                              dp[i-1][j-1]
                                                                                                                                                                                                                                              刪除
                                                                                                                                                                                                                                              dp[i-1][j]
                                                                                                                                                                                                                                              插入
                                                                                                                                                                                                                                              dp[i][j-1]
                                                                                                                                                                                                                                              dp[i][j]
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              # 初始化 base case
                                                                                                                                                                                                                                              +dp[0][0][...] = base
                                                                                                                                                                                                                                              +# 進行狀態轉移
                                                                                                                                                                                                                                              +for 狀態1 in 狀態1的所有取值:
                                                                                                                                                                                                                                              +    for 狀態2 in 狀態2的所有取值:
                                                                                                                                                                                                                                              +        for ...
                                                                                                                                                                                                                                              +            dp[狀態1][狀態2][...] = 求最值(選擇1,選擇2...)
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0053Maximum SubarrayGoEasyO(n)O(n)Dynamic Programming
                                                                                                                                                                                                                                              00720072. Edit DistanceGoHardDynamic Programming
                                                                                                                                                                                                                                              0300Longest-Increasing-SubsequenceGoMedium方法一:O(n^2) 方法二:O(nlogn)O(n)Dynamic Programming
                                                                                                                                                                                                                                              0322Coin ChangeGoMediumO(nm)O(n)Dynamic Programming
                                                                                                                                                                                                                                              0354Russian Doll EnvelopeGoHardDynamic Programming
                                                                                                                                                                                                                                              0509Fibonacci NumberGoEasy很多解法很多解法Dynamic Programming
                                                                                                                                                                                                                                              00700070.Climbing StairsGoEasyO(n)O(n)Dynamic Programming
                                                                                                                                                                                                                                              07460746.Min Cost Climbing StairsGoEasyO(n)O(1)Dynamic Programming
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Sliding Window

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              維護一個窗口, 不斷滑動

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              void slidingWindow(string s, string t){
                                                                                                                                                                                                                                              +    unordered mapneed, window;
                                                                                                                                                                                                                                              +    for (char c:t) need[c++]
                                                                                                                                                                                                                                              +    int left = 0 , right = 0
                                                                                                                                                                                                                                              +    int valid = 0
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +    // 先移動 right 再移動 left. 直到right到達 string的末端
                                                                                                                                                                                                                                              +    while(right < s.size()){
                                                                                                                                                                                                                                              +        // c是將移入窗口的字符
                                                                                                                                                                                                                                              +        char c = s[right]
                                                                                                                                                                                                                                              +        // 右移窗口 
                                                                                                                                                                                                                                              +        right++
                                                                                                                                                                                                                                              +        // 進行窗口內數據的一系列更新
                                                                                                                                                                                                                                              +        // ...
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +        /*** 用來debug 輸出位置 ***/
                                                                                                                                                                                                                                              +        printf("window: [%d, %d)\n",left,right)
                                                                                                                                                                                                                                              +        /************************/
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +        // 判斷左側窗口是否收縮
                                                                                                                                                                                                                                              +        while(window needs shrink){
                                                                                                                                                                                                                                              +           // d是將移出窗口的字符
                                                                                                                                                                                                                                              +           // 左移窗口 
                                                                                                                                                                                                                                              +            left++
                                                                                                                                                                                                                                              +            // 進行窗口內數據的一系列更新
                                                                                                                                                                                                                                              +            // ...
                                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                                              +}
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0209Minimum Size Subarray SumGoMediumO(n^2) / O(n) / O(nlog n)O(1) / O(1) / O(n)Sliding Window
                                                                                                                                                                                                                                              0438Find All Anagrams in a StringGoMediumO(n)O(1)Sliding Window
                                                                                                                                                                                                                                              0567Permutation in StringGoMediumO(n)O(1)Sliding Window
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Sweep Line

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Rolling Sum

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Two Pointers

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              只要array有序, 就應該想到雙指針技巧 +分為兩類 1. "快,慢指針" 2. "左,右指針"

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                              1. 快,慢指針: 主要解決 linkedlist 問題, 典型的判斷 linkedlist 是否包含環
                                                                                                                                                                                                                                              2. +
                                                                                                                                                                                                                                              3. 左,右指針: 主要解決array(或 string)中的問題, 如二分搜尋.
                                                                                                                                                                                                                                              4. +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              https://labuladong.gitee.io/algo/2/21/57/

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0019Remove Nth Node From End of ListGoMediumO(n)O(1)Linked List, Two Pointers
                                                                                                                                                                                                                                              0141Linked List CycleGoEasyO(n)O(1)Linked List, Two Pointers
                                                                                                                                                                                                                                              0283Move ZeroesGoEasyO(n)O(1)Two Pointers
                                                                                                                                                                                                                                              0142Linked List Cycle IIGoMediumO(n)O(1)Linked List, Two Pointers
                                                                                                                                                                                                                                              0344Reverse StringGoEasyO(n)O(1)Two Pointers
                                                                                                                                                                                                                                              0876Middle of the Linked ListGoEasyLinked List, Two Pointers
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Bit Manipulation

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0693Binary Number with Alternating BitsGoEasyO(n)/ O(1)O(1) / O(1)Bit Manipulation
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Union Find

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0721Accounts MergeGoEasyO(n) / O(n log n)O(n) / O(n)Union Find
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                              • DFS 算法可以被認為是回溯算法, BFS算法都是用Queue這種數據結構, 每次將一個截短周圍的所有節點加入Queue.
                                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                                              • BFS 找到的路徑一定是最短的, 但是代價是空間複雜度比DFS大. BFS vs DFS
                                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                                              • 優化: 雙向 BFS 優化, 在 while 開始時做一個判斷. 讓每次都選擇較小的集合進行擴散, +那麼佔用的空間增長速度就會慢一些, 盡可能以最小的空間代價產生 curDepth 和 nextDepth 的交集 +無論單向的 BFS 或是 雙向BFS, 優化過的BFS 空間複雜度都是一樣的
                                                                                                                                                                                                                                              • +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              // 計算從起點 start 到 終點 target 的最點距離
                                                                                                                                                                                                                                              +int BFS(Node start, Node targe){
                                                                                                                                                                                                                                              +    Queue q; // 核心數據結構
                                                                                                                                                                                                                                              +    Set visited; // 避免走回頭路
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +    q.offer(start); // 將起點加入 Queue
                                                                                                                                                                                                                                              +    visited.add(start);
                                                                                                                                                                                                                                              +    int step = 0; // 紀錄擴散的步數
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +    while(q not empty) {
                                                                                                                                                                                                                                              +        int sz = q.size();
                                                                                                                                                                                                                                              +        // 當前 Queue 中的所有節點向四周擴散
                                                                                                                                                                                                                                              +        for (int i = 0 ; i < sz; i++) {
                                                                                                                                                                                                                                              +            Node cur = q.poll();
                                                                                                                                                                                                                                              +            // 這裡判斷是否到達終點
                                                                                                                                                                                                                                              +            if (cur is target) {
                                                                                                                                                                                                                                              +                return step;
                                                                                                                                                                                                                                              +            }
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +            // 將cur 的相鄰節點加入 Queue
                                                                                                                                                                                                                                              +            for (Node x : cur.adj()) {
                                                                                                                                                                                                                                              +                if (x not in visited) {
                                                                                                                                                                                                                                              +                    q.offer(x);
                                                                                                                                                                                                                                              +                    visited.add(x);
                                                                                                                                                                                                                                              +                }
                                                                                                                                                                                                                                              +            }
                                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                                              +        // 在這裡更新步數
                                                                                                                                                                                                                                              +        step++
                                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                                              +}
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0310Minimum Height TreesGoMediumBreadth First Search
                                                                                                                                                                                                                                              0752752. Open the LockGoMediumBreadth First Search
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                                              分析二分搜尋技巧: 不要出現 else, 而是把所有情況用 else if 寫清楚. +計算 mid 時需要防止溢出

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              int binarySearch(int[] nums, int target){
                                                                                                                                                                                                                                              +    int left = 0 , right = ...;
                                                                                                                                                                                                                                              +    while(...) {
                                                                                                                                                                                                                                              +        int mid = left + (right - left)/2
                                                                                                                                                                                                                                              +        if (nums[mid] == target){
                                                                                                                                                                                                                                              +            ...
                                                                                                                                                                                                                                              +        } else if (nums[mid] < target){
                                                                                                                                                                                                                                              +            left = ...
                                                                                                                                                                                                                                              +        } else if (nums[mid] > target){
                                                                                                                                                                                                                                              +            right = ...
                                                                                                                                                                                                                                              +        }
                                                                                                                                                                                                                                              +    }
                                                                                                                                                                                                                                              +    return ...;
                                                                                                                                                                                                                                              +}
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0704704. Binary SearchGoEasy最差:O(long n)
                                                                                                                                                                                                                                              最佳O(1)剛好在中間
                                                                                                                                                                                                                                              迭代: O(1)
                                                                                                                                                                                                                                              遞迴O(log n)
                                                                                                                                                                                                                                              Binary Search
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Minimax

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Graph

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Graph

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Topological Sort

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Tree

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              No.TitleSolutionDifficultyTimeSpaceTopic
                                                                                                                                                                                                                                              0226Invert Binary TreeGoEasyO(n)O(1)Tree
                                                                                                                                                                                                                                              0104Maximum Depth of Binary TreeGoEasyO(n)O(1)Tree
                                                                                                                                                                                                                                              0543Diameter of Binary TreeGoEasyO(n)O(n), O(log(n))Tree, DFS
                                                                                                                                                                                                                                              0110Balanced Binary TreeGoEasyO(n)O(1)Tree, DFS
                                                                                                                                                                                                                                              0100Same TreeGoEasyO(n)O(1)Tree
                                                                                                                                                                                                                                              0105Construct Binary Tree from Preorder and Inorder TraversalGoMediumO(n)O(n)Array
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Tree Traversal

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Binary Search Tree

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Compputational Geometry

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Selected Topics

                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Mathematics

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Random

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Bitwise Manipulation

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              GeeksforGeeks Content

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              TopicTitleNo.SolutionDifficultyTimeComplexitySpaceComplexity
                                                                                                                                                                                                                                              SortingFind Minimum Difference Between Any Two Elements0031GoBasicO(n^2), O(n log n)O(n), O(n)
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +

                                                                                                                                                                                                                                              Codility Content

                                                                                                                                                                                                                                              + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                              Topic Title Solution Difficulty TimeComplexity SpaceComplexity
                                                                                                                                                                                                                                              Lesson 1 + Iterations
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Binary Gap
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(log n) O(1)
                                                                                                                                                                                                                                              Lesson 2 + Array
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Cyclic Rotation
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(1) O(1)
                                                                                                                                                                                                                                              + Odd Occurrences In Array
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n), O(n) O(n), O(1)
                                                                                                                                                                                                                                              Lesson 3 + Time Complexity
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Frog Jmp
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(1) O(1)
                                                                                                                                                                                                                                              + Perm Missing Elem
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(1)
                                                                                                                                                                                                                                              + Tape Equilibrium
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              Lesson 4 + Counting Elements
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Frog River One
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              + Max Counters
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(n+m) O(n)
                                                                                                                                                                                                                                              + Missing Integer
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(n) O(n)
                                                                                                                                                                                                                                              + Perm Check
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              Lesson 5 + Prefix Sums
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Count Div
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(1) O(1)
                                                                                                                                                                                                                                              + Genomic Range Query
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(n+m) O(n)
                                                                                                                                                                                                                                              + MinAvg Two Slice
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(n) O(n)
                                                                                                                                                                                                                                              + Passing Cars
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(1)
                                                                                                                                                                                                                                              Lesson 6 + Sorting
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Distinct
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(nlogn) O(n)
                                                                                                                                                                                                                                              + Max Product of Three
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(nlogn) O(1)
                                                                                                                                                                                                                                              + Number Of Disc Intersections
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(nlogn) O(n)
                                                                                                                                                                                                                                              + Triangle
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(nlogn) O(n)
                                                                                                                                                                                                                                              Lesson 7 + Stacks and Queues
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Brackets
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              + Fish
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              + Nesting
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(1)
                                                                                                                                                                                                                                              + Stone Wall
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              Lesson 8 + Leader
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Dominator
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(1)
                                                                                                                                                                                                                                              + EquiLeader
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              Lesson 9 + Maximum slice problem
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Max Profit
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(1)
                                                                                                                                                                                                                                              + Max Slice Sum
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(n) O(n)
                                                                                                                                                                                                                                              + Max Double Slice Sum
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(n) O(n)
                                                                                                                                                                                                                                              Lesson 10 + Prime and composite numbers
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Count Factors
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(sqrt(n)) O(1)
                                                                                                                                                                                                                                              + Flags
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(n) O(n)
                                                                                                                                                                                                                                              + MinPerimeterRectangle
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(sqrt(n))) O(1)
                                                                                                                                                                                                                                              + Peaks
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O( n*log( log(n) )) O(n)
                                                                                                                                                                                                                                              Lesson 11 + Sieve of Eratosthenes
                                                                                                                                                                                                                                              (質數篩)
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Count Non Divisible
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(N * log(N)) O(n)
                                                                                                                                                                                                                                              + Count Semiprimes
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(N*log(log(N))+M) O(N+M)
                                                                                                                                                                                                                                              Lesson 12 + Euclidean algorithm
                                                                                                                                                                                                                                              (輾轉相除法 or 歐幾里得算法)
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Chocolates By Numbers
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless O(log(N + M)) O(1)
                                                                                                                                                                                                                                              + Common Prime Divisors
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(Z * log(max(A) + max(B))**2) O(1)
                                                                                                                                                                                                                                              Lesson 13 + Fibonacci numbers
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + FibFrog
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + Go
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable O(N * log(N)) O(N)
                                                                                                                                                                                                                                              + Ladder
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable
                                                                                                                                                                                                                                              Lesson 14 + Binary search algorithm
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + MinMaxDivision
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable
                                                                                                                                                                                                                                              + NailingPlanks
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable
                                                                                                                                                                                                                                              Lesson 15 + Caterpillar method
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + AbsDistinct
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless
                                                                                                                                                                                                                                              + CountDistinctSlices
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless
                                                                                                                                                                                                                                              + CountTriangles
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless
                                                                                                                                                                                                                                              + MinAbsSumOfTwo
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable
                                                                                                                                                                                                                                              Lesson 16 + Greedy algorithms
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + MaxNonoverlappingSegments
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless
                                                                                                                                                                                                                                              + TieRopes
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Painless
                                                                                                                                                                                                                                              Lesson 17 + Dynamic programming
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + MinAbsSum
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Ambitious
                                                                                                                                                                                                                                              + NumberSolitaire
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              Respectable
                                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                                              Reference

                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                              + + +
                                                                                                                                                                                                                                              + +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                              + +

                                                                                                                                                                                                                                              results matching ""

                                                                                                                                                                                                                                              +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                + +

                                                                                                                                                                                                                                                No results matching ""

                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                + + + + + + +
                                                                                                                                                                                                                                                + + +
                                                                                                                                                                                                                                                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/makefile b/makefile new file mode 100644 index 000000000..6a3aa977e --- /dev/null +++ b/makefile @@ -0,0 +1,24 @@ +all: build + +build: summary + gitbook build + +start: summary + gitbook serve . + +summary: + book sm -i _book node_modules + +deploy_firebase: summary build + firebase login + firebase deploy + +tag: summary + @echo "Version: $(VERSION)" + git tag -a $(VERSION) -m "$(VERSION)" + git push origin $(VERSION) + +sync: + git submodule update --recursive --remote + +.PHONY: clean build all \ No newline at end of file diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..ecf7f0785 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,785 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "@babel/code-frame": { + "version": "7.23.5", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", + "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", + "requires": { + "@babel/highlight": "^7.23.4", + "chalk": "^2.4.2" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + } + } + }, + "@babel/helper-validator-identifier": { + "version": "7.22.20", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", + "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==" + }, + "@babel/highlight": { + "version": "7.23.4", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", + "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", + "requires": { + "@babel/helper-validator-identifier": "^7.22.20", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0" + }, + "dependencies": { + "ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "requires": { + "color-convert": "^1.9.0" + } + }, + "chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "requires": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + } + }, + "color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "requires": { + "color-name": "1.1.3" + } + }, + "color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==" + } + } + }, + "@mermaid-js/mermaid-cli": { + "version": "9.4.0", + "resolved": "https://registry.npmjs.org/@mermaid-js/mermaid-cli/-/mermaid-cli-9.4.0.tgz", + "integrity": "sha512-/Nqs8Xtasw5wvop1PPiqmSx5SUxq/yARH+0EhEHAx8MVdbZXtUnzuK+Yv6NgpD2/Fb84/N3jF08zmIiJSyT5Lg==", + "requires": { + "chalk": "^5.0.1", + "commander": "^10.0.0", + "puppeteer": "^19.0.0" + } + }, + "@puppeteer/browsers": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-0.5.0.tgz", + "integrity": "sha512-Uw6oB7VvmPRLE4iKsjuOh8zgDabhNX67dzo8U/BB0f9527qx+4eeUs+korU98OhG5C4ubg7ufBgVi63XYwS6TQ==", + "requires": { + "debug": "4.3.4", + "extract-zip": "2.0.1", + "https-proxy-agent": "5.0.1", + "progress": "2.0.3", + "proxy-from-env": "1.1.0", + "tar-fs": "2.1.1", + "unbzip2-stream": "1.4.3", + "yargs": "17.7.1" + } + }, + "@types/node": { + "version": "20.11.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.7.tgz", + "integrity": "sha512-GPmeN1C3XAyV5uybAf4cMLWT9fDWcmQhZVtMFu7OR32WjrqGG+Wnk2V1d0bmtUyE/Zy1QJ9BxyiTih9z8Oks8A==", + "optional": true, + "requires": { + "undici-types": "~5.26.4" + } + }, + "@types/yauzl": { + "version": "2.10.3", + "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", + "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==", + "optional": true, + "requires": { + "@types/node": "*" + } + }, + "agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "requires": { + "debug": "4" + } + }, + "ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==" + }, + "ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "requires": { + "color-convert": "^2.0.1" + } + }, + "argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" + }, + "bl": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", + "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", + "requires": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "requires": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==" + }, + "callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==" + }, + "chalk": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.3.0.tgz", + "integrity": "sha512-dLitG79d+GV1Nb/VYcCDFivJeK1hiukt9QjRNVOsUtTy1rR1YJsmpGGTZ3qJos+uw7WmWF4wUwBd9jxjocFC2w==" + }, + "chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==" + }, + "chromium-bidi": { + "version": "0.4.7", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.4.7.tgz", + "integrity": "sha512-6+mJuFXwTMU6I3vYLs6IL8A1DyQTPjCfIL971X0aMPVGRbGnNfl6i6Cl0NMbxi2bRYLGESt9T2ZIMRM5PAEcIQ==", + "requires": { + "mitt": "3.0.0" + } + }, + "cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "requires": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + } + }, + "color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "requires": { + "color-name": "~1.1.4" + } + }, + "color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "commander": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz", + "integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==" + }, + "cosmiconfig": { + "version": "8.1.3", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.1.3.tgz", + "integrity": "sha512-/UkO2JKI18b5jVMJUp0lvKFMpa/Gye+ZgZjKD+DGEN9y7NRcf/nK1A0sp67ONmKtnDCNMS44E6jrk0Yc3bDuUw==", + "requires": { + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "parse-json": "^5.0.0", + "path-type": "^4.0.0" + } + }, + "cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "requires": { + "node-fetch": "2.6.7" + } + }, + "crypto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/crypto/-/crypto-1.0.1.tgz", + "integrity": "sha512-VxBKmeNcqQdiUQUW2Tzq0t377b54N2bMtXO/qiLa+6eRRmmC4qT3D4OnTGoT/U6O9aklQ/jTwbOtRMTTY8G0Ig==" + }, + "datauri": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/datauri/-/datauri-3.0.0.tgz", + "integrity": "sha512-NeDFuUPV1YCpCn8MUIcDk1QnuyenUHs7f4Q5P0n9FFA0neKFrfEH9esR+YMW95BplbYfdmjbs0Pl/ZGAaM2QHQ==", + "requires": { + "image-size": "0.8.3", + "mimer": "1.1.0" + } + }, + "debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "requires": { + "ms": "2.1.2" + } + }, + "devtools-protocol": { + "version": "0.0.1107588", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1107588.tgz", + "integrity": "sha512-yIR+pG9x65Xko7bErCUSQaDLrO/P1p3JUzEk7JCU4DowPcGHkTGUGQapcfcLc4qj0UaALwZ+cr0riFgiqpixcg==" + }, + "emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "end-of-stream": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz", + "integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==", + "requires": { + "once": "^1.4.0" + } + }, + "error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "requires": { + "is-arrayish": "^0.2.1" + } + }, + "escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==" + }, + "extract-zip": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", + "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", + "requires": { + "@types/yauzl": "^2.9.1", + "debug": "^4.1.1", + "get-stream": "^5.1.0", + "yauzl": "^2.10.0" + } + }, + "fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "requires": { + "pend": "~1.2.0" + } + }, + "fs-constants": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", + "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==" + }, + "get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" + }, + "get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "requires": { + "pump": "^3.0.0" + } + }, + "gitbook-plugin-mermaid-newface": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/gitbook-plugin-mermaid-newface/-/gitbook-plugin-mermaid-newface-4.1.0.tgz", + "integrity": "sha512-sh5po2TgtIwh8VyrCUZzCU7BzMb9C+Om8NMD/sLMky2ITgMSYL3nVBwCYhmLPk6tadid4Tia5tJF2eiYipy6tw==", + "requires": { + "@mermaid-js/mermaid-cli": "^9.1.2", + "crypto": "^1.0.1", + "datauri": "^3.0.0" + } + }, + "gitbook-plugin-sitemap": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gitbook-plugin-sitemap/-/gitbook-plugin-sitemap-1.2.0.tgz", + "integrity": "sha512-PSJ2BuuNot5CczwzjSCIyRRtom87nPXuD4pEtuVUEg10D8ZBpT3r9+/el6XRzwf8gyC4Sf3QKqreD/ia/G5V4g==", + "requires": { + "sitemap": "1.5.0" + } + }, + "gitbook-plugin-sitemap-general": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/gitbook-plugin-sitemap-general/-/gitbook-plugin-sitemap-general-0.1.1.tgz", + "integrity": "sha512-Oe3ClhXzuxdsEnN7uhhMLIylXeMSFuW0YZhAe+Wk0agAXvlcBgOk61gnnp1Nde4QJ7lu2Vi2XNh2sI4uPGJT5g==", + "requires": { + "sitemap": "1.5.0" + } + }, + "graceful-fs": { + "version": "4.2.10", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.10.tgz", + "integrity": "sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA==" + }, + "has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==" + }, + "https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "requires": { + "agent-base": "6", + "debug": "4" + } + }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" + }, + "image-size": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-0.8.3.tgz", + "integrity": "sha512-SMtq1AJ+aqHB45c3FsB4ERK0UCiA2d3H1uq8s+8T0Pf8A3W4teyBQyaFaktH6xvZqh+npwlKU7i4fJo0r7TYTg==", + "requires": { + "queue": "6.0.1" + } + }, + "import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "requires": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==" + }, + "is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==" + }, + "js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==" + }, + "js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "requires": { + "argparse": "^2.0.1" + } + }, + "json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==" + }, + "lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==" + }, + "mimer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/mimer/-/mimer-1.1.0.tgz", + "integrity": "sha512-y9dVfy2uiycQvDNiAYW6zp49ZhFlXDMr5wfdOiMbdzGM/0N5LNR6HTUn3un+WUQcM0koaw8FMTG1bt5EnHJdvQ==" + }, + "mitt": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.0.tgz", + "integrity": "sha512-7dX2/10ITVyqh4aOSVI9gdape+t9l2/8QxHrFmUXu4EEUpdlxl6RudZUPZoc+zuY2hk1j7XxVroIVIan/pD/SQ==" + }, + "mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node-fetch": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "requires": { + "whatwg-url": "^5.0.0" + } + }, + "once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "requires": { + "wrappy": "1" + } + }, + "parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "requires": { + "callsites": "^3.0.0" + } + }, + "parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "requires": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + } + }, + "path-type": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-type/-/path-type-4.0.0.tgz", + "integrity": "sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==" + }, + "pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==" + }, + "progress": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz", + "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==" + }, + "proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, + "pump": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", + "integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==", + "requires": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "puppeteer": { + "version": "19.11.1", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-19.11.1.tgz", + "integrity": "sha512-39olGaX2djYUdhaQQHDZ0T0GwEp+5f9UB9HmEP0qHfdQHIq0xGQZuAZ5TLnJIc/88SrPLpEflPC+xUqOTv3c5g==", + "requires": { + "@puppeteer/browsers": "0.5.0", + "cosmiconfig": "8.1.3", + "https-proxy-agent": "5.0.1", + "progress": "2.0.3", + "proxy-from-env": "1.1.0", + "puppeteer-core": "19.11.1" + } + }, + "puppeteer-core": { + "version": "19.11.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-19.11.1.tgz", + "integrity": "sha512-qcuC2Uf0Fwdj9wNtaTZ2OvYRraXpAK+puwwVW8ofOhOgLPZyz1c68tsorfIZyCUOpyBisjr+xByu7BMbEYMepA==", + "requires": { + "@puppeteer/browsers": "0.5.0", + "chromium-bidi": "0.4.7", + "cross-fetch": "3.1.5", + "debug": "4.3.4", + "devtools-protocol": "0.0.1107588", + "extract-zip": "2.0.1", + "https-proxy-agent": "5.0.1", + "proxy-from-env": "1.1.0", + "tar-fs": "2.1.1", + "unbzip2-stream": "1.4.3", + "ws": "8.13.0" + } + }, + "queue": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/queue/-/queue-6.0.1.tgz", + "integrity": "sha512-AJBQabRCCNr9ANq8v77RJEv73DPbn55cdTb+Giq4X0AVnNVZvMHlYp7XlQiN+1npCZj1DuSmaA2hYVUUDgxFDg==", + "requires": { + "inherits": "~2.0.3" + } + }, + "readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "requires": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + } + }, + "require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==" + }, + "resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==" + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "sitemap": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/sitemap/-/sitemap-1.5.0.tgz", + "integrity": "sha512-AGevBYvwFaoBsZoWClv8qlaA3lpoPCUnNh2zxIHl3coZXXD5U2+GKtkMBS3pXvl5NXvzN4R0392gN4YrIpSUmQ==", + "requires": { + "underscore": "^1.7.0", + "url-join": "^0.0.1" + } + }, + "string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "requires": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + } + }, + "string_decoder": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "requires": { + "safe-buffer": "~5.2.0" + } + }, + "strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "requires": { + "ansi-regex": "^5.0.1" + } + }, + "supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "requires": { + "has-flag": "^3.0.0" + } + }, + "tar-fs": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", + "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "requires": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "tar-stream": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", + "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "requires": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + } + }, + "through": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", + "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==" + }, + "tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "unbzip2-stream": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", + "integrity": "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==", + "requires": { + "buffer": "^5.2.1", + "through": "^2.3.8" + } + }, + "underscore": { + "version": "1.13.6", + "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.6.tgz", + "integrity": "sha512-+A5Sja4HP1M08MaXya7p5LvjuM7K6q/2EaC0+iovj/wOcMsTzMvDFbasi/oSapiwOlt252IqsKqPjCl7huKS0A==" + }, + "undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", + "optional": true + }, + "url-join": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/url-join/-/url-join-0.0.1.tgz", + "integrity": "sha512-H6dnQ/yPAAVzMQRvEvyz01hhfQL5qRWSEt7BX8t9DqnPw9BjMb64fjIRq76Uvf1hkHp+mTZvEVJ5guXOT0Xqaw==" + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "requires": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "requires": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + } + }, + "wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "ws": { + "version": "8.13.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", + "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==" + }, + "y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==" + }, + "yargs": { + "version": "17.7.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.1.tgz", + "integrity": "sha512-cwiTb08Xuv5fqF4AovYacTFNxk62th7LKJ6BL9IGUpTJrWoU7/7WdQGTP2SjKf1dUNBGzDd28p/Yfs/GI6JrLw==", + "requires": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + } + }, + "yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==" + }, + "yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "requires": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..f7ebc2fbb --- /dev/null +++ b/package.json @@ -0,0 +1,8 @@ +{ + "dependencies": { + "gitbook-plugin-mermaid-newface": "^4.1.0", + "gitbook-plugin-sitemap": "^1.2.0", + "gitbook-plugin-sitemap-general": "^0.1.1", + "graceful-fs": "^4.2.10" + } +} diff --git a/search_plus_index.json b/search_plus_index.json new file mode 100644 index 000000000..a3bd3dd1b --- /dev/null +++ b/search_plus_index.json @@ -0,0 +1 @@ +{"./":{"url":"./","title":"Introduction","keywords":"","body":"Leetcode in Golang Leetcode, Codility , GeekforGeeks algorithms exercises written in Golang. https://kimi0230.github.io/LeetcodeGolang/ leetcode Content Leetcode in Golang leetcode Content Data Structure Array \\& String Matrix Linked List HashSet \\& HashMap Stack \\& Queue Heap \\& Priority Queue Heap ๆœ‰ๅนพๅ€‹็‰น่‰ฒ๏ผš heap sort Disjoint Set Union Trie Binary Indexed Tree Design Data Structures Algorithm Greedy Sort Multiple Pointers Backtracking (ๅ›žๆบฏๆณ•). DFS DFS \\& BFS Dynamic Programming Sliding Window Sweep Line Rolling Sum Two Pointers Bit Manipulation Union Find Breadth First Search Binary Search Minimax Graph Graph Topological Sort Tree Tree Traversal Binary Search Tree Compputational Geometry Selected Topics Mathematics Random Bitwise Manipulation GeeksforGeeks Content Codility Content Reference Data Structure Array & String No. Title Solution Difficulty Time Space Topic 0001 Two Sum Go Easy O(n) O(n) Array 0003 Longest Substring Without Repeating Characters Go Medium O(n) O(1) Array, Sliding Window 0015 3 Sum Go Medium O(n^2) O(n) Array 0027 Remove Element Go Easy O(n) O(1) Array 0035 Search Insert Position Go Easy O(n), O(logn) O(1) Array 0049 Search Insert Position Go Medium O(kn) O(kn) Array 0059 Spiral Matrix II Go Medium O(n) O(n^2) Array 0088 Merge Sorted Array Go Easy O(n) O(1) Array 0217 0217.Contains Duplicate Go Easy O(n) O(n) Array 0242 0242.Valid Anagram Go Easy O(n) O(n) Array 0409 409. Longest Palindrome Go Easy O(n) O(1) Array 0380 0380.Insert Delete GetRandom O(1) Go Medium O(1) O(n) Array 0381 0381.Insert Delete GetRandom O(1) Duplicates allowed Go Medium O(1) O(n) Array 0412 0412.Fizz Buzz Go Easy O(n) O(n) Array, string 1195 1195.Fizz Buzz Multithreaded Go Medium O(n) Array, string,Concurrency 0238 238. Product of Array Except Self Go Medium O(n) Array, string, Prefix Sum 0128 128. Longest Consecutive Sequence Go Medium O(n) O(n) Array, Hash Table, Union Find Matrix Linked List No. Title Solution Difficulty Time Space Topic 0019 Remove Nth Node From End of List Go Medium O(n) O(1) Linked List, Two Pointers 0141 Linked List Cycle Go Easy O(n) O(1) Linked List, Two Pointers 0142 Linked List Cycle II Go Medium O(n) O(1) Linked List, Two Pointers 0203 Remove Linked List Elements Go Easy O(n) O(1) Linked List 0206 Reverse Linked List Go Easy O(n) O(1) Linked List 0876 Middle of the Linked List Go Easy Linked List, Two Pointers 0021 Merge Two Sorted Lists Go Easy O(log n) O(1) Linked List 0002 Add Two Number Go Medium O(max(m,n)) O(1) Linked List HashSet & HashMap Stack & Queue No. Title Solution Difficulty Time Space Topic 0020 Valid Parentheses Go Easy O(n) O(n) Stack 0094 Binary Tree Inorder Traversal Go Medium O(n) O(1) Stack Heap & Priority Queue Heap ็ธฝๆ˜ฏ่ƒฝ่ฎ“ๆ•ดๆฃตๆจน็•ถไธญๆœ€ๅคงๆˆ–ๆœ€ๅฐๅ€ผ็ถญๆŒๅœจroot็ฏ€้ปžไธŠ Heap ๆœ‰ๅนพๅ€‹็‰น่‰ฒ๏ผš ๅธธ่ฆ‹ๆžถๆง‹ๆ˜ฏๅƒ binary tree ้‚ฃๆจฃ ไฟๆŒ balanced max heap ็š„ root ๆ˜ฏๆœ€ๅคงๅ€ผ๏ผ›min heap ็š„ root ๅ‰‡ๆ˜ฏๆœ€ๅฐๅ€ผ ้›–็„ถๆ˜ฏ tree๏ผŒๅปๅพˆ้ฉๅˆๆ”พๅœจ array ไธญ่™•็† heap sort ๆ นๆ“šๅฎš็พฉ heap ็š„ root ไธ€ๅฎšๆ˜ฏๆœ€ๅคง(ๅ‡่จญๆ˜ฏ max heap)๏ผŒไนŸๅฐฑๆ˜ฏ่ชช๏ผŒ็„กๅบๆ•ธๅˆ—็ถ“้Ž heapify ๅ†ไฝœ n ๆฌก root deletion ๅ–ๅ‡บๆœ€ๅคงๅ€ผ๏ผŒๅฐฑๅฏไปฅๅพ—ๅˆฐๆŽ’ๅบ็š„็ตๆžœใ€‚ ๆœ€ๅพŒๅฐฑๅพ—ๅˆฐ heap sort ็š„ worst case ๆ™‚้–“่ค‡้›œๅบฆ O(nlogn) ็š„็ตๆžœใ€‚ ๅฏๆ˜ฏ quick sort ็š„ worst case ๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏ O(nยฒ)๏ผŒๆ€Ž้บผ quick sort ็š„ๆ™‚้–“่ค‡้›œๅบฆๆฏ”่ผƒ็ณŸ็ณ•ๅปๆฏ”่ผƒๅ—ๆญก่ฟŽ๏ผŸ google ็š„็ตๆžœๆ˜ฏ่ชช heap sort ๆฏ”่ผƒไธๅˆฉๆ–ผ caching ๅฐๆ–ผ spatial locality ๆฉŸๅˆถ๏ผŒ่ ปๆœ‰้“็†็š„้˜ฟใ€‚ https://www.zhihu.com/question/23873747 https://rust-algo.club/sorting/heapsort/index.html No. Title Solution Difficulty Time Space Topic 0703 Kth Largest Element in a Stream Go Easy O(K + (N-K)logK) O(k) Heap, Priority Queue 1046 Last Stone Weight Go Easy O(nlogn) O(n) Heap, Priority Queue 0347 Top K Frequent Elements Go Medium O(Nlogโกk) O(n) Heap, Priority Queue, Quick Sort Disjoint Set Union Trie Binary Indexed Tree Design Data Structures Algorithm Greedy Sort No. Title Solution Difficulty Time Space Topic 0075 Sort Colors Go Medium O(n) O(1) Sort 0215 Kth Largest Element in an Array Go Medium O(n) O(logn) Sort Multiple Pointers Backtracking (ๅ›žๆบฏๆณ•). DFS DFS. ่งฃๆฑบไธ€ๅ€‹ๅ›žๆบฏๅ•้กŒ, ๅฏฆ้š›ไธŠๅฐฑๆ˜ฏไธ€ๅ€‹ๆฑบ็ญ–ๆจน็š„้ๆญท้Ž็จ‹. ็ฎ—ๆ˜ฏไธ€ๅ€‹ๆšดๅŠ›็š„็ชฎ่ˆ‰็ฎ—ๆณ• ่ทฏๅพ‘๏ผšไนŸๅฐฑๆ˜ฏๅทฒ็ถ“ๅšๅ‡บ็š„้ธๆ“‡ใ€‚ ้ธๆ“‡ๅˆ—่กจ๏ผšไนŸๅฐฑๆ˜ฏไฝ ็•ถๅ‰ๅฏไปฅๅš็š„้ธๆ“‡ใ€‚ ็ตๆŸๆขไปถ๏ผšไนŸๅฐฑๆ˜ฏๅˆฐ้”ๆฑบ็ญ–ๆจนๅบ•ๅฑค๏ผŒ็„กๆณ•ๅ†ๅš้ธๆ“‡็š„ๆขไปถใ€‚ https://www.bilibili.com/video/BV1P5411N7Xc result = [] def backtrack(่ทฏๅพ‘, ้ธๆ“‡ๅˆ—่กจ): if ๆปฟ่ถณ็ตๆŸๆขไปถ: result.add(่ทฏๅพ‘) return for ้ธๆ“‡ in ้ธๆ“‡ๅˆ—่กจ: ๅš้ธๆ“‡(ๅ‰ๅบ) backtrack(่ทฏๅพ‘, ้ธๆ“‡ๅˆ—่กจ) ๆ’ค้Šท้ธๆ“‡(ๅพŒๅบ) No. Title Solution Difficulty Time Space Topic 0046 Permutations (ๅ…จๆŽ’ๅˆ—) Go Medium O(n) O(n) Backtracking 0078 Subsets Go Medium O(n^2) O(n) Backtracking DFS & BFS ๆ‰พๆœ€็Ÿญ่ทฏๅพ‘็”จBFS, ๅ…ถไป–ๆ™‚็”จDFS็”จๅพ—ๅคšไธ€ไบ›, ๅ› ็‚บ้ž่ฟด่ผƒๅฅฝๅฏซ ๅ‡่จญๆœ‰ๆฃตๆปฟ็š„ไบŒๅ‰ๆจน,็ฏ€้ปžๆ•ธ็‚บ N. ๅฐDFSไพ†่ชช็ฉบ้–“่ค‡้›œๅบฆๅฐฑๆ˜ฏ้ž่ฟด, ๆœ€ๅฃž็š„ๆƒ…ๆณๅฐฑๆ˜ฏๆจน็š„้ซ˜ๅบฆ O(log N) BFS็ฎ—ๆณ•, Queueๆฏๆฌก้ƒฝๆœƒๅญ˜ไบŒๅ‰ๆจนไธ€ๅฑค็š„็ฏ€้ปž, ๆœ€ๅฃž็š„ๆƒ…ๆณไธ‹็ฉบ้–“่ค‡้›œๅบฆๆ‡‰่ฉฒๅฐฑๆ˜ฏๆจน็š„ๆœ€ไธ‹ๅฑค็š„ๆ•ธ้‡, ไนŸๅฐฑๆ˜ฏ N/2. ็ฉบ้–“่ค‡้›œๅบฆ O(N) DFS๏ผˆๆทฑๅบฆๅ„ชๅ…ˆๆœ็ดข๏ผ‰้€šๅธธไฝฟ็”จๅ †ๆฃง๏ผˆStack๏ผ‰ไพ†ๅฏฆ็พใ€‚ๅœจDFSไธญ๏ผŒๆ‚จ้ฆ–ๅ…ˆ่™•็†ไธ€ๅ€‹็ฏ€้ปž๏ผŒ็„ถๅพŒๅฐ‡ๅ…ถๅญ็ฏ€้ปžๆŒ‰ๆŸ็จฎ้ †ๅบๆŽจๅ…ฅๅ †ๆฃงไธญ๏ผŒๆŽฅ่‘—็นผ็บŒ่™•็†ๅ †ๆฃง้ ‚้ƒจ็š„็ฏ€้ปž๏ผŒ็›ดๅˆฐๅ †ๆฃง็‚บ็ฉบใ€‚ BFS๏ผˆๅปฃๅบฆๅ„ชๅ…ˆๆœ็ดข๏ผ‰ๅ‰‡ไฝฟ็”จ้šŠๅˆ—๏ผˆQueue๏ผ‰ไพ†ๅฏฆ็พใ€‚ๅœจBFSไธญ๏ผŒๆ‚จ้ฆ–ๅ…ˆ่™•็†ไธ€ๅ€‹็ฏ€้ปž๏ผŒ็„ถๅพŒๅฐ‡ๅ…ถๅญ็ฏ€้ปžๆŒ‰ๆŸ็จฎ้ †ๅบๆŽ’้šŠ๏ผŒๆŽฅ่‘—็นผ็บŒ่™•็†้šŠๅˆ—็š„ๅ‰็ซฏ็ฏ€้ปž๏ผŒ็›ดๅˆฐ้šŠๅˆ—็‚บ็ฉบใ€‚ No. Title Solution Difficulty Time Space Topic 0695 Max Area of Island Go Medium O(m*n) O(m*n) DFS & BFS 0733 Flood Fill Go Easy O(m*n) O(m*n) DFS & BFS Dynamic Programming ๅ‹•ๆ…‹่ฆๅŠƒๅ•้กŒ็š„ไธ€่ˆฌๅฝขๅผๅฐฑๆ˜ฏๆฑ‚ๆœ€ๅ€ผ, ๆœ€้•ท้žๅขžๅญๅบๅˆ—, ๆœ€ๅฐ็ทจ่ผฏ่ท้›ข็ญ‰. ๆ ธๅฟƒๅ•้กŒๆ˜ฏ็ชฎ่ˆ‰ ้‡็–Šๅญๅ•้กŒ memory table DP table ๆœ€ๅ„ชๅญ็ตๆง‹ ็‹€ๆ…‹่ฝ‰็งปๆ–น็จ‹ๅผ ้€™ๅ•้กŒ็š„ base case (ๆœ€็ฐกๅ–ฎๆƒ…ๆณ) ๆ˜ฏไป€้บผ? ้€™ๅ•้กŒๆœ‰ไป€้บผ็‹€ๆ…‹ ๅฐๆ–ผๆฏๅ€‹็‹€ๆ…‹, ๅฏไปฅๅšๅ‡บไป€้บผ้ธๆ“‡, ไฝฟๅพ—็‹€ๆ…‹็™ผ็”Ÿๆ”น่ฎŠ ๅฆ‚ไฝ•ๅฎš็พฉ dp ๆ•ธ็ต„/ๅ‡ฝๆ•ธ็š„ๅซ็พฉไพ†่กจ็พ็‹€ๆ…‹ๅ’Œ้ธๆ“‡? ๆ›ฟๆ› /่ทณ้Ž dp[i-1][j-1] ๅˆช้™ค dp[i-1][j] ๆ’ๅ…ฅ dp[i][j-1] dp[i][j] # ๅˆๅง‹ๅŒ– base case dp[0][0][...] = base # ้€ฒ่กŒ็‹€ๆ…‹่ฝ‰็งป for ็‹€ๆ…‹1 in ็‹€ๆ…‹1็š„ๆ‰€ๆœ‰ๅ–ๅ€ผ๏ผš for ็‹€ๆ…‹2 in ็‹€ๆ…‹2็š„ๆ‰€ๆœ‰ๅ–ๅ€ผ๏ผš for ... dp[็‹€ๆ…‹1][็‹€ๆ…‹2][...] = ๆฑ‚ๆœ€ๅ€ผ(้ธๆ“‡1๏ผŒ้ธๆ“‡2...) No. Title Solution Difficulty Time Space Topic 0053 Maximum Subarray Go Easy O(n) O(n) Dynamic Programming 0072 0072. Edit Distance Go Hard Dynamic Programming 0300 Longest-Increasing-Subsequence Go Medium ๆ–นๆณ•ไธ€:O(n^2) ๆ–นๆณ•ไบŒ:O(nlogn) O(n) Dynamic Programming 0322 Coin Change Go Medium O(nm) O(n) Dynamic Programming 0354 Russian Doll Envelope Go Hard Dynamic Programming 0509 Fibonacci Number Go Easy ๅพˆๅคš่งฃๆณ• ๅพˆๅคš่งฃๆณ• Dynamic Programming 0070 0070.Climbing Stairs Go Easy O(n) O(n) Dynamic Programming 0746 0746.Min Cost Climbing Stairs Go Easy O(n) O(1) Dynamic Programming Sliding Window ็ถญ่ญทไธ€ๅ€‹็ช—ๅฃ, ไธๆ–ทๆป‘ๅ‹• void slidingWindow(string s, string t){ unordered mapneed, window; for (char c:t) need[c++] int left = 0 , right = 0 int valid = 0 // ๅ…ˆ็งปๅ‹• right ๅ†็งปๅ‹• left. ็›ดๅˆฐrightๅˆฐ้” string็š„ๆœซ็ซฏ while(right No. Title Solution Difficulty Time Space Topic 0209 Minimum Size Subarray Sum Go Medium O(n^2) / O(n) / O(nlog n) O(1) / O(1) / O(n) Sliding Window 0438 Find All Anagrams in a String Go Medium O(n) O(1) Sliding Window 0567 Permutation in String Go Medium O(n) O(1) Sliding Window Sweep Line Rolling Sum Two Pointers ๅช่ฆarrayๆœ‰ๅบ, ๅฐฑๆ‡‰่ฉฒๆƒณๅˆฐ้›™ๆŒ‡้‡ๆŠ€ๅทง ๅˆ†็‚บๅ…ฉ้กž 1. \"ๅฟซ,ๆ…ขๆŒ‡้‡\" 2. \"ๅทฆ,ๅณๆŒ‡้‡\" ๅฟซ,ๆ…ขๆŒ‡้‡: ไธป่ฆ่งฃๆฑบ linkedlist ๅ•้กŒ, ๅ…ธๅž‹็š„ๅˆคๆ–ท linkedlist ๆ˜ฏๅฆๅŒ…ๅซ็’ฐ ๅทฆ,ๅณๆŒ‡้‡: ไธป่ฆ่งฃๆฑบarray(ๆˆ– string)ไธญ็š„ๅ•้กŒ, ๅฆ‚ไบŒๅˆ†ๆœๅฐ‹. https://labuladong.gitee.io/algo/2/21/57/ No. Title Solution Difficulty Time Space Topic 0019 Remove Nth Node From End of List Go Medium O(n) O(1) Linked List, Two Pointers 0141 Linked List Cycle Go Easy O(n) O(1) Linked List, Two Pointers 0283 Move Zeroes Go Easy O(n) O(1) Two Pointers 0142 Linked List Cycle II Go Medium O(n) O(1) Linked List, Two Pointers 0344 Reverse String Go Easy O(n) O(1) Two Pointers 0876 Middle of the Linked List Go Easy Linked List, Two Pointers Bit Manipulation No. Title Solution Difficulty Time Space Topic 0693 Binary Number with Alternating Bits Go Easy O(n)/ O(1) O(1) / O(1) Bit Manipulation Union Find No. Title Solution Difficulty Time Space Topic 0721 Accounts Merge Go Easy O(n) / O(n log n) O(n) / O(n) Union Find Breadth First Search DFS ็ฎ—ๆณ•ๅฏไปฅ่ขซ่ช็‚บๆ˜ฏๅ›žๆบฏ็ฎ—ๆณ•, BFS็ฎ—ๆณ•้ƒฝๆ˜ฏ็”จQueue้€™็จฎๆ•ธๆ“š็ตๆง‹, ๆฏๆฌกๅฐ‡ไธ€ๅ€‹ๆˆช็Ÿญๅ‘จๅœ็š„ๆ‰€ๆœ‰็ฏ€้ปžๅŠ ๅ…ฅQueue. BFS ๆ‰พๅˆฐ็š„่ทฏๅพ‘ไธ€ๅฎšๆ˜ฏๆœ€็Ÿญ็š„, ไฝ†ๆ˜ฏไปฃๅƒนๆ˜ฏ็ฉบ้–“่ค‡้›œๅบฆๆฏ”DFSๅคง. BFS vs DFS ๅ„ชๅŒ–: ้›™ๅ‘ BFS ๅ„ชๅŒ–, ๅœจ while ้–‹ๅง‹ๆ™‚ๅšไธ€ๅ€‹ๅˆคๆ–ท. ่ฎ“ๆฏๆฌก้ƒฝ้ธๆ“‡่ผƒๅฐ็š„้›†ๅˆ้€ฒ่กŒๆ“ดๆ•ฃ, ้‚ฃ้บผไฝ”็”จ็š„็ฉบ้–“ๅขž้•ท้€Ÿๅบฆๅฐฑๆœƒๆ…ขไธ€ไบ›, ็›กๅฏ่ƒฝไปฅๆœ€ๅฐ็š„็ฉบ้–“ไปฃๅƒน็”ข็”Ÿ curDepth ๅ’Œ nextDepth ็š„ไบค้›† ็„ก่ซ–ๅ–ฎๅ‘็š„ BFS ๆˆ–ๆ˜ฏ ้›™ๅ‘BFS, ๅ„ชๅŒ–้Ž็š„BFS ็ฉบ้–“่ค‡้›œๅบฆ้ƒฝๆ˜ฏไธ€ๆจฃ็š„ // ่จˆ็ฎ—ๅพž่ตท้ปž start ๅˆฐ ็ต‚้ปž target ็š„ๆœ€้ปž่ท้›ข int BFS(Node start, Node targe){ Queue q; // ๆ ธๅฟƒๆ•ธๆ“š็ตๆง‹ Set visited; // ้ฟๅ…่ตฐๅ›ž้ ญ่ทฏ q.offer(start); // ๅฐ‡่ตท้ปžๅŠ ๅ…ฅ Queue visited.add(start); int step = 0; // ็ด€้Œ„ๆ“ดๆ•ฃ็š„ๆญฅๆ•ธ while(q not empty) { int sz = q.size(); // ็•ถๅ‰ Queue ไธญ็š„ๆ‰€ๆœ‰็ฏ€้ปžๅ‘ๅ››ๅ‘จๆ“ดๆ•ฃ for (int i = 0 ; i No. Title Solution Difficulty Time Space Topic 0310 Minimum Height Trees Go Medium Breadth First Search 0752 752. Open the Lock Go Medium Breadth First Search Binary Search ๅˆ†ๆžไบŒๅˆ†ๆœๅฐ‹ๆŠ€ๅทง: ไธ่ฆๅ‡บ็พ else, ่€Œๆ˜ฏๆŠŠๆ‰€ๆœ‰ๆƒ…ๆณ็”จ else if ๅฏซๆธ…ๆฅš. ่จˆ็ฎ— mid ๆ™‚้œ€่ฆ้˜ฒๆญขๆบขๅ‡บ int binarySearch(int[] nums, int target){ int left = 0 , right = ...; while(...) { int mid = left + (right - left)/2 if (nums[mid] == target){ ... } else if (nums[mid] target){ right = ... } } return ...; } No. Title Solution Difficulty Time Space Topic 0704 704. Binary Search Go Easy ๆœ€ๅทฎ:O(long n) ๆœ€ไฝณO(1)ๅ‰›ๅฅฝๅœจไธญ้–“ ่ฟญไปฃ: O(1) ้ž่ฟดO(log n) Binary Search Minimax Graph Graph Topological Sort Tree No. Title Solution Difficulty Time Space Topic 0226 Invert Binary Tree Go Easy O(n) O(1) Tree 0104 Maximum Depth of Binary Tree Go Easy O(n) O(1) Tree 0543 Diameter of Binary Tree Go Easy O(n) O(n), O(log(n)) Tree, DFS 0110 Balanced Binary Tree Go Easy O(n) O(1) Tree, DFS 0100 Same Tree Go Easy O(n) O(1) Tree 0105 Construct Binary Tree from Preorder and Inorder Traversal Go Medium O(n) O(n) Array Tree Traversal Binary Search Tree Compputational Geometry Selected Topics Mathematics Random Bitwise Manipulation GeeksforGeeks Content Topic Title No. Solution Difficulty TimeComplexity SpaceComplexity Sorting Find Minimum Difference Between Any Two Elements 0031 Go Basic O(n^2), O(n log n) O(n), O(n) Codility Content Topic Title Solution Difficulty TimeComplexity SpaceComplexity Lesson 1 Iterations Binary Gap Go Painless O(log n) O(1) Lesson 2 Array Cyclic Rotation Go Painless O(1) O(1) Odd Occurrences In Array Go Painless O(n), O(n) O(n), O(1) Lesson 3 Time Complexity Frog Jmp Go Painless O(1) O(1) Perm Missing Elem Go Painless O(n) O(1) Tape Equilibrium Go Painless O(n) O(n) Lesson 4 Counting Elements Frog River One Go Painless O(n) O(n) Max Counters Go Respectable O(n+m) O(n) Missing Integer Go Respectable O(n) O(n) Perm Check Go Painless O(n) O(n) Lesson 5 Prefix Sums Count Div Go Respectable O(1) O(1) Genomic Range Query Go Respectable O(n+m) O(n) MinAvg Two Slice Go Respectable O(n) O(n) Passing Cars Go Painless O(n) O(1) Lesson 6 Sorting Distinct Go Painless O(nlogn) O(n) Max Product of Three Go Painless O(nlogn) O(1) Number Of Disc Intersections Go Respectable O(nlogn) O(n) Triangle Go Painless O(nlogn) O(n) Lesson 7 Stacks and Queues Brackets Go Painless O(n) O(n) Fish Go Painless O(n) O(n) Nesting Go Painless O(n) O(1) Stone Wall Go Painless O(n) O(n) Lesson 8 Leader Dominator Go Painless O(n) O(1) EquiLeader Go Painless O(n) O(n) Lesson 9 Maximum slice problem Max Profit Go Painless O(n) O(1) Max Slice Sum Go Painless O(n) O(n) Max Double Slice Sum Go Respectable O(n) O(n) Lesson 10 Prime and composite numbers Count Factors Go Painless O(sqrt(n)) O(1) Flags Go Respectable O(n) O(n) MinPerimeterRectangle Go Painless O(sqrt(n))) O(1) Peaks Go Respectable O( n*log( log(n) )) O(n) Lesson 11 Sieve of Eratosthenes (่ณชๆ•ธ็ฏฉ) Count Non Divisible Go Respectable O(N * log(N)) O(n) Count Semiprimes Go Respectable O(N*log(log(N))+M) O(N+M) Lesson 12 Euclidean algorithm (่ผพ่ฝ‰็›ธ้™คๆณ• or ๆญๅนพ้‡Œๅพ—็ฎ—ๆณ•) Chocolates By Numbers Go Painless O(log(N + M)) O(1) Common Prime Divisors Go Respectable O(Z * log(max(A) + max(B))**2) O(1) Lesson 13 Fibonacci numbers FibFrog Go Respectable O(N * log(N)) O(N) Ladder Respectable Lesson 14 Binary search algorithm MinMaxDivision Respectable NailingPlanks Respectable Lesson 15 Caterpillar method AbsDistinct Painless CountDistinctSlices Painless CountTriangles Painless MinAbsSumOfTwo Respectable Lesson 16 Greedy algorithms MaxNonoverlappingSegments Painless TieRopes Painless Lesson 17 Dynamic programming MinAbsSum Ambitious NumberSolitaire Respectable Reference leetcode leetcode-cn halfrost anakin wufenggirl GeeksforGeeks Codility GitHub: labuladong/fucking-algorithm(labuladong ็ฎ—ๆณ•ๅฐๆŠ„) https://cses.fi/ https://github.com/neetcode-gh/leetcode ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Algorithms/A1B2C3/":{"url":"Algorithms/A1B2C3/","title":"A1B2C3: Two Go Routine Print A1B2C3....Z26","summary":"Two Go Routine Print A1B2C3....Z26","keywords":"","body":"A1B2C3 tagsstart Algorithm Golang A1B2C3 tagsstop ็”จๅ…ฉๅ€‹ go routine ๅฐๅ‡บ A1B2C3....Z26 Two Go Routine Print A1B2C3....Z26 Channle With Buffer func ChannelWBuffer() { abc := make(chan struct{}, 1) num := make(chan struct{}, 1) done := make(chan struct{}) abc Channel Without Buffer func ChannelWOBuffer() { abc := make(chan struct{}) num := make(chan struct{}) done := make(chan struct{}) go func() { for i := 65; i Wait Group func WGLock() { abcMux := sync.Mutex{} numMux := sync.Mutex{} numMux.Lock() wg := sync.WaitGroup{} wg.Add(2) go func() { defer wg.Done() for i := 65; i Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Algorithms/A1B2C3 cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz BenchmarkChannelWBuffer-4 79159 14612 ns/op 344 B/op 5 allocs/op BenchmarkChannelWOBuffer-4 83068 14451 ns/op 344 B/op 5 allocs/op BenchmarkWGLock-4 51303 23072 ns/op 96 B/op 5 allocs/op PASS ok LeetcodeGolang/Algorithms/A1B2C3 4.092s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Algorithms/Find_Target_Last_Index/findtargetlastindex.html":{"url":"Algorithms/Find_Target_Last_Index/findtargetlastindex.html","title":"Find Target Last Index","summary":"ๅœจๆœ‰ๅบ็š„arrayไธญ ๆ‰พๅ‡บtargetๅœจarrayไธญๆœ€ๅพŒ็š„indexๆ˜ฏไป€้บผ","keywords":"","body":"Find Target Last Index tagsstart Interview Algorithms Go Easy Find Target Last Index Right Bound Left Bound tagsstop ๅœจๆœ‰ๅบ็š„arrayไธญ ๆ‰พๅ‡บtargetๅœจarrayไธญๆœ€ๅพŒ็š„indexๆ˜ฏไป€้บผ ็”จไบŒๅˆ†ๆœๅฐ‹ๆณ•ๅŽปๆ‰พ, RightBound ๅฏๅƒ่€ƒ https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0704.Binary-Search/main.go ๆ–นๆณ•ไธ€ func Solution(nums []int, target int) int { left, right := 0, len(nums)-1 result := -1 for left > 1) if nums[mid] == target { // ็นผ็บŒๆ‰พ, ็ธฎๅฐๅณ้‚Š if target == nums[right] { result = right break } else { right-- } } else if nums[mid] target { // ๅพ€ๅทฆๆ‰พ right = mid - 1 } } return result } ๆ–นๆณ•ไบŒ ้ž่ฟด func SolutionRecursive(nums []int, target int) int { left, right := 0, len(nums)-1 return findTarget(nums, left, right, target) } func findTarget(nums []int, left, right, target int) int { if left > right { return -1 } mid := int(uint(left+right) >> 1) if nums[mid] == target { if nums[right] == target { return right } else { return findTarget(nums, mid, right-1, target) } } else if nums[mid] go test -benchmem -run=none LeetcodeGolang/Algorithms/Find_Target_Last_Index -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Algorithms/Find_Target_Last_Index cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkSolution-8 54216429 24.75 ns/op 0 B/op 0 allocs/op BenchmarkSolutionRecursive-8 40756744 27.75 ns/op 0 B/op 0 allocs/op PASS ok LeetcodeGolang/Algorithms/Find_Target_Last_Index 2.537s RightBound // ๆœ‰้ปž้กžไผผ nums ๅคงๆ–ผ target็š„ๅ…ƒ็ด ๆœ‰ๅนพๅ€‹ func RightBound(nums []int, target int) (index int) { lenght := len(nums) if lenght >1 mid := int(uint(right+left) >> 1) if nums[mid] == target { // ๆณจๆ„:่ฆ็นผ็บŒๆ‰พๅณ้‚Š, ๆ‰€ไปฅๆŠŠๅทฆ้‚Š่ฎŠๅคง=mid+1 left = mid + 1 } else if nums[mid] target { // ๆ‰พๅทฆ้‚Š right = mid - 1 } } // ้ƒฝๆฒ’ๆ‰พๅˆฐ ๆณจๆ„:right่ถŠ็•Œๆƒ…ๆณ if right LeftBound // ๆœ‰้ปž้กžไผผ nums ๅฐๆ–ผ target็š„ๅ…ƒ็ด ๆœ‰ๅนพๅ€‹ func LeftBound(nums []int, target int) (index int) { lenght := len(nums) if lenght >1 mid := int(uint(right+left) >> 1) if nums[mid] == target { // ่ฆ็นผ็บŒๆ‰พๅทฆ้‚Š, ๆ‰€ไปฅๆŠŠๅณ้‚Š่ฎŠๅฐ right = mid - 1 } else if nums[mid] target { // ๆ‰พๅทฆ้‚Š right = mid - 1 } } // ้ƒฝๆฒ’ๆ‰พๅˆฐ ๆณจๆ„: left่ถŠ็•Œๆƒ…ๆณ if left >= lenght || nums[left] != target { return -1 } return left } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/":{"url":"Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/","title":"Intersection Of Two Sorted Arrays Using In Place Approach","summary":"","keywords":"","body":"Intersection of Two Sorted Arrays using In Place Approach tagsstart Golang Algorithms Intersection tagsstop Intersection of Two Sorted Arrays using In Place Approach ่ฆๅœจๅŽŸๅœฐ๏ผˆin-place๏ผ‰่งฃๆฑบ้€™ๅ€‹ๅ•้กŒ๏ผŒๅฏไปฅไฝฟ็”จ้›™ๆŒ‡้‡็š„ๆ–นๆณ•ใ€‚ๅ‡่จญ็ตฆๅฎš็š„ๅ…ฉๅ€‹ๆ•ธ็ต„ๅˆ†ๅˆฅ็‚บAๅ’ŒB๏ผŒๅฎƒๅ€‘ๅทฒ็ถ“ๆŒ‰ๅ‡ๅบๆŽ’ๅบใ€‚ ้ฆ–ๅ…ˆ๏ผŒๆˆ‘ๅ€‘ๅฏไปฅๅˆๅง‹ๅŒ–ๅ…ฉๅ€‹ๆŒ‡้‡iๅ’Œjๅˆ†ๅˆฅๆŒ‡ๅ‘Aๅ’ŒB็š„่ตทๅง‹ไฝ็ฝฎ๏ผŒ็„ถๅพŒ้–‹ๅง‹้€ฒ่กŒๆฏ”่ผƒใ€‚ๅฆ‚ๆžœA[i]ๅฐๆ–ผB[j]๏ผŒๅ‰‡็งปๅ‹•ๆŒ‡้‡iๅ‘ๅพŒ็งปๅ‹•ไธ€ไฝ๏ผ›ๅฆ‚ๆžœA[i]ๅคงๆ–ผB[j]๏ผŒๅ‰‡็งปๅ‹•ๆŒ‡้‡jๅ‘ๅพŒ็งปๅ‹•ไธ€ไฝ๏ผ›ๅฆ‚ๆžœA[i]็ญ‰ๆ–ผB[j]๏ผŒๅ‰‡ๅฐ‡่ฉฒๅ€ผๆทปๅŠ ๅˆฐ็ตๆžœไธญ๏ผŒไธฆๅฐ‡ๅ…ฉๅ€‹ๆŒ‡้‡้ƒฝๅ‘ๅพŒ็งปๅ‹•ไธ€ไฝใ€‚ ้‡่ค‡ไธŠ่ฟฐๆญฅ้ฉŸ๏ผŒ็›ดๅˆฐๅ…ถไธญไธ€ๅ€‹ๆ•ธ็ต„็š„ๆŒ‡้‡้”ๅˆฐๆ•ธ็ต„ๆœซๅฐพ็‚บๆญขใ€‚ๆœ€็ต‚๏ผŒๅพ—ๅˆฐ็š„็ตๆžœๅฐฑๆ˜ฏๅ…ฉๅ€‹ๆ•ธ็ต„็š„ไบค้›†ใ€‚ package intersection func FindIntersection(A, B []int) []int { var i, j int = 0, 0 result := []int{} for i B[j] { j++ } else { result = append(result, A[i]) i++ j++ } } return result } func TestFindIntersection(t *testing.T) { var tests = []struct { arg1 []int arg2 []int want []int }{ { arg1: []int{1, 3, 4, 6, 7}, arg2: []int{2, 4, 6, 8, 9}, want: []int{4, 6}, }, } for _, tt := range tests { if got := FindIntersection(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { t.Errorf(\"got = %v, want = %v\", got, tt.want) } } } TODO: ๅปถไผธ 349. Intersection of Two Arrays (easy) 350. Intersection of Two Arrays II ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Algorithms/SearchGraph/":{"url":"Algorithms/SearchGraph/","title":"Search Graph In Golang","summary":"","keywords":"","body":"Search Graph tagsstart Golang Algorithms Search Graph BFS tagsstop 2 / \\ / \\ 1 - 3 - 5 - 7 \\ / \\ 6 \\ / 4 ไธ€ๅ€‹Graph,้šจไพฟๆŒ‡ๅฎšไธ€ๅ€‹่ตท้ปž, ๅ„ชๅ…ˆprintๅ‡บๅ‘จๅœ็š„ๅ€ผ // 1 -> [2, 3, 4] // 2 -> [1, 5] // 3 -> [1, 5] // 4 -> [1, 6] // 5 -> [2, 3, 7] // 6 -> [4, 7] // 7 -> [5, 6] // print : 1,2,3,4,5,6,7 // Also this is valid : 1,4,3,2,6,5,7 ไพ‹ๅฆ‚ ้–‹ๅง‹ไฝ็ฝฎ1, print : 1,2,3,4,5,6, ่งฃๆณ• ็”จBFS(Queue) ๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏO(V+E)๏ผŒๅ…ถไธญVๆ˜ฏๅœ–ไธญ็ฏ€้ปž็š„ๆ•ธ้‡๏ผŒEๆ˜ฏๅœ–ไธญ้‚Š็š„ๆ•ธ้‡ ่งฃ็ญ” package searchgraph import ( \"LeetcodeGolang/Utility/crud\" \"LeetcodeGolang/structures\" \"fmt\" \"strconv\" jsoniter \"github.com/json-iterator/go\" ) func fetchNeighbours(node int) []int { crud := crud.NewCrud(\"https://hackbear.tv/graph/\" + strconv.Itoa(node)) var result = []int{} if got := crud.Get(); got.Error != nil { // fmt.Printf(\"got = %v\", got) } else { var json = jsoniter.ConfigCompatibleWithStandardLibrary json.Unmarshal([]byte(got.Response), &result) } return result } /* 2 / \\ / \\ 1 - 3 - 5 - 7 \\ / \\ 6 \\ / 4 */ // 1 -> [2, 3, 4] // 2 -> [1, 5] // 3 -> [1, 5] // 4 -> [1, 6] // 5 -> [2, 3, 7] // 6 -> [4, 7] // 7 -> [5, 6] // print : 1,2,3,4,5,6,7 // Also this is valid : 1,4,3,2,6,5,7 // You will be working on this part /* ๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏO(V+E)๏ผŒๅ…ถไธญVๆ˜ฏๅœ–ไธญ็ฏ€้ปž็š„ๆ•ธ้‡๏ผŒEๆ˜ฏๅœ–ไธญ้‚Š็š„ๆ•ธ้‡ */ func SearchGraph(start int) { queue := structures.NewQueue() queue.Push(start) visit := make(map[int][]int) for queue.Len() > 0 { node := queue.Pop() if _, ok := visit[node]; !ok { fmt.Printf(\"%d \", node) neighours := fetchNeighbours(node) visit[node] = neighours for _, neighour := range neighours { if _, ok := visit[neighour]; !ok { queue.Push(neighour) } } } } } func SearchGraph2(start int) { queue := structures.NewQueue() queue.Push(start) visited := make(map[int]bool) for queue.Len() > 0 { node := queue.Pop() if !visited[node] { fmt.Printf(\"%d \", node) visited[node] = true neighbors := fetchNeighbours(node) for _, neighbor := range neighbors { if !visited[neighbor] { queue.Push(neighbor) } } } } } Reference https://www.youtube.com/watch?v=BkszA-MvjXA https://web.ntnu.edu.tw/~algo/Graph.html ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Algorithms/WeightedEditDistance/":{"url":"Algorithms/WeightedEditDistance/","title":"Weighted Edit Distance","summary":"","keywords":"","body":"WeightedEditDistance tagsstart Golang WeightedEditDistance Dynamic Programming tagsstop WeightedEditDistance ๆ˜ฏไธ€ๅ€‹่จˆ็ฎ—ๅธถๆœ‰ๆฌŠ้‡็š„็ทจ่ผฏ่ท้›ข็š„ๅ‡ฝๅผใ€‚็ทจ่ผฏ่ท้›ขๆ˜ฏ่กก้‡ๅ…ฉๅ€‹ๅญ—ไธฒไน‹้–“็š„็›ธไผผๅบฆ็š„ๆŒ‡ๆจ™๏ผŒ่กจ็คบๅฐ‡ไธ€ๅ€‹ๅญ—ไธฒ่ฝ‰ๆ›็‚บๅฆไธ€ๅ€‹ๅญ—ไธฒๆ‰€้œ€็š„ๆœ€ๅฐๆ“ไฝœๆ•ธ้‡ใ€‚ ๅœจๆจ™ๆบ–็š„็ทจ่ผฏ่ท้›ข็ฎ—ๆณ•ไธญ๏ผŒๆ“ไฝœๅŒ…ๆ‹ฌๆ’ๅ…ฅใ€ๅˆช้™คๅ’Œๆ›ฟๆ›ๅญ—็ฌฆใ€‚ๆฏๅ€‹ๆ“ไฝœ้ƒฝ่ขซ่ช็‚บๅ…ทๆœ‰็›ธๅŒ็š„ไปฃๅƒนใ€‚็„ถ่€Œ๏ผŒๅœจ WeightedEditDistance ไธญ๏ผŒๆฏๅ€‹ๅญ—็ฌฆ็š„ๆ“ไฝœไปฃๅƒนๅฏไปฅไธๅŒ๏ผŒไธฆ็”ฑไธ€ๅ€‹ๆฌŠ้‡ๆ˜ ๅฐ„่กจๆŒ‡ๅฎšใ€‚ ๅ‡ฝๅผ WeightedEditDistance ๆŽฅๅ—ๅ…ฉๅ€‹ๅญ—็ฌฆไธฒ word1 ๅ’Œ word2๏ผŒไปฅๅŠไธ€ๅ€‹ๆฌŠ้‡ๆ˜ ๅฐ„่กจ weightsใ€‚่ฉฒๆ˜ ๅฐ„่กจๅฐ‡ๆฏๅ€‹ๅญ—็ฌฆๆ˜ ๅฐ„ๅˆฐๅ…ถ็›ธๆ‡‰็š„ๆฌŠ้‡ๅ€ผ๏ผŒ็”จๆ–ผ่จˆ็ฎ—ๆ“ไฝœ็š„ไปฃๅƒนใ€‚ ่ฉฒๅ‡ฝๅผไฝฟ็”จๅ‹•ๆ…‹่ฆๅŠƒ็š„ๆ–นๆณ•่จˆ็ฎ—็ทจ่ผฏ่ท้›ขใ€‚ๅฎƒๅ‰ตๅปบไธ€ๅ€‹ไบŒ็ถญ็Ÿฉ้™ฃ dp๏ผŒๅ…ถไธญ dp[i][j] ่กจ็คบๅฐ‡ word1[:i] ่ฝ‰ๆ›็‚บ word2[:j] ็š„ๆœ€ๅฐๆ“ไฝœไปฃๅƒนใ€‚ ็ฎ—ๆณ•็š„ๆ ธๅฟƒๆ˜ฏ้ๆญท dp ็Ÿฉ้™ฃไธฆ่จˆ็ฎ—ๆฏๅ€‹ๅ–ฎๅ…ƒๆ ผ็š„ๅ€ผใ€‚ๅฆ‚ๆžœ word1[i-1] ็ญ‰ๆ–ผ word2[j-1]๏ผŒๅ‰‡่กจ็คบๅ…ฉๅ€‹ๅญ—็ฌฆ็›ธ็ญ‰๏ผŒไธ้œ€่ฆ้€ฒ่กŒๆ“ไฝœ๏ผŒๆ‰€ไปฅ dp[i][j] ็ญ‰ๆ–ผ dp[i-1][j-1]ใ€‚ๅฆๅ‰‡๏ผŒ้œ€่ฆ่€ƒๆ…ฎๆ’ๅ…ฅใ€ๅˆช้™คๅ’Œๆ›ฟๆ›ๆ“ไฝœ็š„ไปฃๅƒน๏ผŒไธฆๅ–ๅ…ถไธญๆœ€ๅฐ็š„ไฝœ็‚บ dp[i][j] ็š„ๅ€ผใ€‚ ๆœ€็ต‚๏ผŒๅ‡ฝๅผ่ฟ”ๅ›ž dp[m][n]๏ผŒๅ…ถไธญ m ๅ’Œ n ๅˆ†ๅˆฅ็‚บ word1 ๅ’Œ word2 ็š„้•ทๅบฆ๏ผŒ่กจ็คบๅฐ‡ๆ•ดๅ€‹ๅญ—ไธฒ word1 ่ฝ‰ๆ›็‚บ word2 ็š„ๆœ€ๅฐๆ“ไฝœไปฃๅƒนใ€‚ ไฝฟ็”จ WeightedEditDistance ๅ‡ฝๅผ๏ผŒๆ‚จๅฏไปฅๆ นๆ“šๅญ—็ฌฆ็š„ๆฌŠ้‡ๅ€ผ่จˆ็ฎ—ๅธถๆœ‰่‡ชๅฎš็พฉๆ“ไฝœไปฃๅƒน็š„็ทจ่ผฏ่ท้›ข๏ผŒไปฅๆ›ดๅฅฝๅœฐๅๆ˜ ๅ…ฉๅ€‹ๅญ—ไธฒไน‹้–“็š„็›ธไผผๆ€งใ€‚ ้กŒ็›ฎๅคงๆ„ weightededitdistance ้›–็„ถไธๆ˜ฏไธ€ๅ€‹็‰นๅฎš็š„LeetCodeๅ•้กŒ๏ผŒไฝ†ๅฎƒๆถ‰ๅŠๅˆฐไธ€ๅ€‹ๆฆ‚ๅฟต๏ผšๅŠ ๆฌŠ็ทจ่ผฏ่ท้›ข๏ผˆWeighted Edit Distance๏ผ‰ใ€‚ ๅŠ ๆฌŠ็ทจ่ผฏ่ท้›ขๆ˜ฏๆŒ‡ๅœจๅ…ฉๅ€‹ๅญ—ไธฒไน‹้–“้€ฒ่กŒ็ทจ่ผฏๆ“ไฝœ๏ผˆๆ’ๅ…ฅใ€ๅˆช้™คใ€ๆ›ฟๆ›๏ผ‰ๆ™‚๏ผŒๆฏๅ€‹ๆ“ไฝœๅ…ทๆœ‰ไธๅŒ็š„ๆˆๆœฌๆˆ–ๆฌŠ้‡ใ€‚่ฉฒๅ•้กŒ่ฆๆฑ‚่จˆ็ฎ—ๅพžไธ€ๅ€‹ๅญ—ไธฒ่ฝ‰ๆ›ๅˆฐๅฆไธ€ๅ€‹ๅญ—ไธฒ็š„ๆœ€ๅฐ็ธฝๆˆๆœฌๆˆ–ๆฌŠ้‡ใ€‚ ่งฃ้กŒๆ€่ทฏ ่งฃๆฑบๅŠ ๆฌŠ็ทจ่ผฏ่ท้›ขๅ•้กŒ็š„ๅธธ็”จๆ–นๆณ•ๆ˜ฏไฝฟ็”จๅ‹•ๆ…‹่ฆๅŠƒ๏ผˆDynamic Programming๏ผ‰ใ€‚ ๅ‰ตๅปบไธ€ๅ€‹ไบŒ็ถญๆ•ธ็ต„dp๏ผŒๅ…ถไธญdp[i][j]่กจ็คบๅฐ‡ๅญ—ไธฒ1็š„ๅ‰iๅ€‹ๅญ—็ฌฆ่ฝ‰ๆ›็‚บๅญ—ไธฒ2็š„ๅ‰jๅ€‹ๅญ—็ฌฆ็š„ๆœ€ๅฐๅŠ ๆฌŠ็ทจ่ผฏ่ท้›ขใ€‚ ๅˆๅง‹ๅŒ–dp็Ÿฉ้™ฃ็š„็ฌฌไธ€่กŒๅ’Œ็ฌฌไธ€ๅˆ—๏ผŒๅˆ†ๅˆฅ่กจ็คบๅฐ‡็ฉบๅญ—ไธฒ่ฝ‰ๆ›็‚บๅญ—ไธฒ1ๅ’Œๅญ—ไธฒ2็š„ๆˆๆœฌ๏ผŒๆ นๆ“šๅ…ท้ซ”ๅ•้กŒ่จญ็ฝฎๅˆๅง‹ๅ€ผใ€‚ ้ๆญทdp็Ÿฉ้™ฃ๏ผŒ่จˆ็ฎ—ๆฏๅ€‹dp[i][j]็š„ๅ€ผ๏ผŒๆ นๆ“šไปฅไธ‹ไธ‰็จฎๆƒ…ๆณ้€ฒ่กŒ้ธๆ“‡๏ผš ๅฆ‚ๆžœๅญ—ไธฒ1็š„็ฌฌiๅ€‹ๅญ—็ฌฆ็ญ‰ๆ–ผๅญ—ไธฒ2็š„็ฌฌjๅ€‹ๅญ—็ฌฆ๏ผŒๅ‰‡dp[i][j]็ญ‰ๆ–ผdp[i-1][j-1]๏ผŒๅณไธ้œ€่ฆ้€ฒ่กŒ็ทจ่ผฏๆ“ไฝœ๏ผŒ็นผๆ‰ฟๅ‰ไธ€ๅ€‹็‹€ๆ…‹็š„็ทจ่ผฏ่ท้›ขใ€‚ ๅฆๅ‰‡๏ผŒdp[i][j]็ญ‰ๆ–ผๆ’ๅ…ฅๆ“ไฝœ็š„ๆˆๆœฌๅŠ ไธŠdp[i][j-1]๏ผŒๅˆช้™คๆ“ไฝœ็š„ๆˆๆœฌๅŠ ไธŠdp[i-1][j]๏ผŒๆ›ฟๆ›ๆ“ไฝœ็š„ๆˆๆœฌๅŠ ไธŠdp[i-1][j-1]๏ผŒๅ–้€™ไธ‰็จฎๆ“ไฝœ็š„ๆœ€ๅฐๅ€ผใ€‚ ๆœ€็ต‚๏ผŒdp[m][n]๏ผˆๅ…ถไธญmๅ’Œnๅˆ†ๅˆฅ็‚บๅ…ฉๅ€‹ๅญ—ไธฒ็š„้•ทๅบฆ๏ผ‰ๅณ็‚บๅ…ฉๅ€‹ๅญ—ไธฒ็š„ๆœ€ๅฐๅŠ ๆฌŠ็ทจ่ผฏ่ท้›ขใ€‚ ๆ›ฟๆ› /่ทณ้Ž dp[i-1][j-1] ๅˆช้™ค dp[i-1][j] ๆ’ๅ…ฅ dp[i][j-1] dp[i][j] ๆ™‚้–“่ค‡้›œๅบฆ: ๅ‹•ๆ…‹่ฆๅŠƒ็š„้ๆญท้Ž็จ‹้œ€่ฆ่จˆ็ฎ—ๅ’Œๅกซๅ……dp็Ÿฉ้™ฃ็š„ๆฏๅ€‹ๅ…ƒ็ด ๏ผŒๅ› ๆญคๆ™‚้–“่ค‡้›œๅบฆ็‚บO(m*n)๏ผŒๅ…ถไธญmๅ’Œnๅˆ†ๅˆฅ็‚บๅ…ฉๅ€‹ๅญ—ไธฒ็š„้•ทๅบฆใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ: ้œ€่ฆไฝฟ็”จไธ€ๅ€‹ไบŒ็ถญๆ•ธ็ต„dpไพ†ไฟๅญ˜ไธญ้–“็ตๆžœ๏ผŒๅ› ๆญค็ฉบ้–“่ค‡้›œๅบฆ็‚บO(m*n)ใ€‚ ่งฃ็ญ” package weightededitdistance import \"fmt\" func WeightedEditDistance(word1, word2 string, weights map[rune]int) int { m, n := len(word1), len(word2) // ๅ‰ตๅปบไบŒ็ถญ็Ÿฉ้™ฃ็”จๆ–ผไฟๅญ˜็ทจ่ผฏ่ท้›ข // dp๏ผŒๅ…ถไธญ dp[i][j] ่กจ็คบๅฐ‡ word1[:i] ่ฝ‰ๆ›็‚บ word2[:j] ็š„ๆœ€ๅฐๆ“ไฝœไปฃๅƒน dp := make([][]int, m+1) for i := 0; i ็›ธ้—œ 0072.Edit-Distance ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"CodeSignal/":{"url":"CodeSignal/","title":"Code Signal","keywords":"","body":"Code Signal Reference https://app.codesignal.com/arcade/intro/level-1 https://github.com/abrar-abu/golanee/main https://github.com/crusty0gphr/bank-request-processor https://github.com/abrar-mahedavi/challenges/tree/main ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"CodeSignal/Bank-Requests/":{"url":"CodeSignal/Bank-Requests/","title":"Bank Requests","summary":"Bank Requests","keywords":"","body":"Bank Requests tagsstart CodeSignal Go Bank Requests tagsstop A solution to one of my coding interview questions. Complete solution - written in GoLang Task: You've been asked to program a bot for a popular bank that will automate the management of incoming requests. There are three types of requests the bank can receive: transfer i j sum: request to transfer sum amount of money from the i-th account to the j-th one deposit i sum: request to deposit sum amount of money in the i-th account withdraw i sum: request to withdraw sum amount of money from the i-th account. Your bot should also be able to process invalid requests. There are two types of invalid requests: invalid account number in the requests; deposit / withdrawal of a larger amount of money than is currently available. For the given list of accounts and requests, return the state of accounts after all requests have been processed, or an array of a single element [- ] (please note the minus sign), where is the 1-based index of the first invalid request. Example for accounts = [10, 100, 20, 50, 30] and requests = [\"withdraw 2 10\", \"transfer 5 1 20\", \"deposit 5 20\", \"transfer 3 4 15\"], the output should be bankRequests(accounts, requests) = [30, 90, 5, 65, 30]. accounts = [10, 100, 20, 50, 30] : ไปฃ่กจ ID:1 ๆœ‰10ๅ…ƒ, ID:2 ๆœ‰100ๅ…ƒ ... \"withdraw 2 10\" : ๅพžID:2 ๆ้ ˜ 10ๅ…ƒ, ๆ‰€ไปฅ100-10 ๆœ€ๅพŒๅพ—ๅˆฐaccounts= [10, 90, 20, 50, 30] Here are the states of accounts after each request: \"withdraw 2 10\": [10, 90, 20, 50, 30] \"transfer 5 1 20\": [30, 90, 20, 50, 10] \"deposit 5 20\": [30, 90, 20, 50, 30] \"transfer 3 4 15\": [30, 90, 5, 65, 30], which is the answer For accounts = [20, 1000, 500, 40, 90] and requests = [\"deposit 3 400\", \"transfer 1 2 30\", \"withdraw 4 50\"], the output should be bankRequests(accounts, requests) = [-2]. After the first request, accounts becomes equal to [20, 1000, 900, 40, 90], but the second one turns it into [-10, 1030, 900, 40, 90], which is invalid. Thus, the second request is invalid, and the answer is [-2]. Note that the last request is also invalid, but it shouldn't be included in the answer. ไธญๆ–‡ๆ„ๆ€: ไฝ ่ขซ่ฆๆฑ‚็‚บไธ€ๅฎถ็Ÿฅๅ้Š€่กŒ็ทจๅฏซไธ€ๅ€‹ๆฉŸๅ™จไบบ๏ผŒ่ฉฒๆฉŸๅ™จไบบๅฐ‡่‡ชๅ‹•่™•็†ไพ†่‡ชๅฎขๆˆถ็š„่ซ‹ๆฑ‚ใ€‚้Š€่กŒๅฏ่ƒฝๆœƒๆ”ถๅˆฐไธ‰็จฎ้กžๅž‹็š„่ซ‹ๆฑ‚๏ผš transfer i j sum๏ผšๅพž็ฌฌiๅ€‹ๅธณๆˆถ่ฝ‰็งปsum้‡‘้กๅˆฐ็ฌฌjๅ€‹ๅธณๆˆถ็š„่ซ‹ๆฑ‚ deposit i sum๏ผšๅ‘็ฌฌiๅ€‹ๅธณๆˆถๅญ˜ๅ…ฅsum้‡‘้ก็š„่ซ‹ๆฑ‚ withdraw i sum๏ผšๅพž็ฌฌiๅ€‹ๅธณๆˆถๆๅ–sum้‡‘้ก็š„่ซ‹ๆฑ‚ใ€‚ ไฝ ็š„ๆฉŸๅ™จไบบ้‚„ๆ‡‰่ฉฒ่ƒฝๅค ่™•็†็„กๆ•ˆ็š„่ซ‹ๆฑ‚ใ€‚็„กๆ•ˆ็š„่ซ‹ๆฑ‚ๆœ‰ๅ…ฉ็จฎ้กžๅž‹๏ผš่ซ‹ๆฑ‚ไธญ็š„ๅธณๆˆถ่™Ÿ็ขผ็„กๆ•ˆ๏ผ›ๅญ˜ๆฌพ/ๆๆฌพ้‡‘้กๅคงๆ–ผ็•ถๅ‰ๅฏ็”จ้‡‘้กใ€‚ ๅฐๆ–ผ็ตฆๅฎš็š„ๅธณๆˆถๅˆ—่กจๅ’Œ่ซ‹ๆฑ‚๏ผŒ่ฟ”ๅ›ž่™•็†ๅฎŒๆ‰€ๆœ‰่ซ‹ๆฑ‚ๅพŒ็š„ๅธณๆˆถ็‹€ๆ…‹๏ผŒๆˆ–ๅ–ฎไธ€ๅ…ƒ็ด ็‚บ[- ]็š„ๆ•ธ็ต„๏ผˆ่ซ‹ๆณจๆ„่ฒ ่™Ÿ๏ผ‰๏ผŒๅ…ถไธญ ๆ˜ฏ็ฌฌไธ€ๅ€‹็„กๆ•ˆ่ซ‹ๆฑ‚็š„ๅพž1้–‹ๅง‹็š„็ดขๅผ•ใ€‚ ไปฅaccounts = [10, 100, 20, 50, 30] ๅ’Œ requests = [\"withdraw 2 10\", \"transfer 5 1 20\", \"deposit 5 20\", \"transfer 3 4 15\"] ็‚บไพ‹๏ผŒ่ผธๅ‡บๆ‡‰็‚บ bankRequests(accounts, requests) = [30, 90, 5, 65, 30]ใ€‚ accounts = [10, 100, 20, 50, 30] ไปฃ่กจ๏ผšID:1 ๆœ‰10ๅ…ƒ, ID:2 ๆœ‰100ๅ…ƒ ... \"withdraw 2 10\" ๅพžID:2 ๆ้ ˜ 10ๅ…ƒ๏ผŒๆ‰€ไปฅ100-10 ๆœ€ๅพŒๅพ—ๅˆฐaccounts= [10, 90, 20, 50, 30] ้€™ๆ˜ฏๆฏๅ€‹่ซ‹ๆฑ‚ๅพŒๅธณๆˆถ็š„็‹€ๆ…‹๏ผš \"withdraw 2 10\": [10, 90, 20, 50, 30] \"transfer 5 1 20\": [30, 90, 20, 50, 10] \"deposit 5 20\": [30, 90, 20, 50, 30] \"transfer 3 4 15\": [30, 90, 5, 65, 30]๏ผŒ้€™ๆ˜ฏ็ญ”ๆกˆ ๅฐๆ–ผaccounts = [20, 1000, 500, 40, 90] ๅ’Œ requests = [\"deposit 3 400\", \"transfer 1 2 30\", \"withdraw 4 50\"]๏ผŒ่ผธๅ‡บๆ‡‰็‚บ bankRequests(accounts, requests) = [-2]ใ€‚ ็ฌฌไธ€ๅ€‹่ซ‹ๆฑ‚ๅพŒ๏ผŒๅธณๆˆถ่ฎŠๆˆ [20, 1000, 900, 40, 90]๏ผŒไฝ†็ฌฌไบŒๅ€‹่ซ‹ๆฑ‚ๅฐ‡ๅ…ถ่ฎŠ็‚บ [-10, 1030, 900, 40, 90]๏ผŒ้€™ๆ˜ฏ็„กๆ•ˆ็š„ใ€‚ๅ› ๆญค๏ผŒ็ฌฌไบŒๅ€‹่ซ‹ๆฑ‚็„กๆ•ˆ๏ผŒ็ญ”ๆกˆ็‚บ[-2]ใ€‚่ซ‹ๆณจๆ„ๆœ€ๅพŒไธ€ๅ€‹่ซ‹ๆฑ‚ไนŸๆ˜ฏ็„กๆ•ˆ็š„๏ผŒไฝ†ไธๆ‡‰ๅŒ…ๅซๅœจ็ญ”ๆกˆไธญใ€‚ ่งฃ็ญ” package bankrequests import ( \"errors\" \"fmt\" \"regexp\" \"strconv\" \"strings\" \"sync\" ) var ( errInvaldTransfer = errors.New(\"invalid transfer\") errInvaldWithdraw = errors.New(\"invalid withdraw\") errInvaldDeposit = errors.New(\"invalid deposit\") errUnknownAction = errors.New(\"unknown action\") ) var requestScheme = [][]string{ 3: {\"action\", \"from\", \"amount\"}, 4: {\"action\", \"from\", \"to\", \"amount\"}, } type BankService interface { getActionName() string transfer() error withdraw() error deposit() error } type Bank struct { BankService action string requestId int from int to int amount int balances []int requestFailed bool failedRequest []int mutex sync.RWMutex } func (bank *Bank) getActionName() string { return bank.action } func (bank *Bank) transfer() error { bank.mutex.Lock() defer bank.mutex.Unlock() invalidAmout := bank.balances[bank.from-1] ]`็š„ๆ•ธ็ต„๏ผˆ่ซ‹ๆณจๆ„่ฒ ่™Ÿ๏ผ‰ func (bank *Bank) failedAction() { bank.mutex.Lock() defer bank.mutex.Unlock() failed := []int{-bank.requestId} bank.balances = []int{} bank.requestFailed = true bank.failedRequest = failed } func (bank *Bank) Action() { var requestErr error action := bank.getActionName() // fmt.Println(\"action:\", action) switch action { case \"transfer\": requestErr = bank.transfer() case \"withdraw\": requestErr = bank.withdraw() case \"deposit\": requestErr = bank.deposit() default: requestErr = errUnknownAction } if requestErr != nil { fmt.Println(\"requestErr:\", requestErr) bank.failedAction() } } func extractRequestParams(request string) map[string]interface{} { res := map[string]interface{}{} reqSlice := strToSlice(request) fmt.Println(\"reqSlice:\", reqSlice) // len is 3: {\"action\", \"from\", \"amount\"}, // len is 4: {\"action\", \"from\", \"to\", \"amount\"}, scheme := requestScheme[len(reqSlice)] for i, v := range scheme { res[v] = reqSlice[i] } return res } func strToSlice(str string) []interface{} { var res []interface{} erp := strings.Fields(str) re, err := regexp.Compile(\"[0-9]+\") if err != nil { fmt.Println(\"Error compiling regex:\", err) return nil } for _, v := range erp { if isNum := re.MatchString(v); isNum { if n, _ := strconv.Atoi(v); n != 0 { res = append(res, n) } } else { res = append(res, v) } } return res } func bankRequests(requests []string, balances []int) []int { var res []int for index, request := range requests { reqParams := extractRequestParams(request) bank := NewBank() bank.requestId = index + 1 bank.action = reqParams[\"action\"].(string) bank.amount = reqParams[\"amount\"].(int) bank.from = reqParams[\"from\"].(int) if _, ok := reqParams[\"to\"]; ok { bank.to = reqParams[\"to\"].(int) } bank.balances = balances bank.Action() if bank.requestFailed { return bank.failedRequest } res = bank.balances } return res } unit test package bankrequests import ( \"reflect\" \"testing\" ) var tests = []struct { arg1 []string arg2 []int want []int }{ { []string{ \"transfer 1 4 10\", \"deposit 3 10\", \"withdraw 5 15\", }, []int{20, 30, 10, 90, 60}, []int{10, 30, 20, 100, 45}, }, { []string{ \"transfer 1 4 40\", \"deposit 3 10\", \"withdraw 5 65\", }, []int{20, 30, 10, 90, 60}, []int{-1}, }, { []string{ \"withdraw 2 10\", \"transfer 5 1 20\", \"deposit 5 20\", \"transfer 3 4 15\", }, []int{10, 100, 20, 50, 30}, []int{30, 90, 5, 65, 30}, }, { []string{ \"deposit 3 400\", \"transfer 1 2 30\", \"withdraw 4 50\", }, []int{20, 1000, 500, 40, 90}, []int{-2}, }, } func TestBankRequests(t *testing.T) { for _, tt := range tests { if got := bankRequests(tt.arg1, tt.arg2); !reflect.DeepEqual(got, tt.want) { t.Errorf(\"got = %v, want = %v\", got, tt.want) } } } Reference https://github.com/crusty0gphr/bank-request-processor/tree/master ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0001.Iterations/Binary-Gap/":{"url":"Codility/Lesson/0001.Iterations/Binary-Gap/","title":"Binary Gap","summary":"Binary Gap","keywords":"","body":"BinaryGap tagsstart Codility Go Iterations Painless Bitwise Manipulation tagsstop START Find longest sequence of zeros in binary representation of an integer. ้กŒ็›ฎ A binary gap within a positive integer N is any maximal sequence of consecutive zeros that is surrounded by ones at both ends in the binary representation of N. For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps. Write a function: func Solution(N int) int that, given a positive integer N, returns the length of its longest binary gap. The function should return 0 if N doesn't contain a binary gap. For example, given N = 1041 the function should return 5, because N has binary representation 10000010001 and so its longest binary gap is of length 5. Given N = 32 the function should return 0, because N has binary representation '100000' and thus no binary gaps. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..2,147,483,647]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่ผธๅ…ฅๆญฃๆ•ดๆ•ธ, ๆ‰พๅ‡บๆญคๆ•ธๅœจไบŒ้€ฒไฝ,ๅ…ฉๅ€‹bitๅ€ผ็‚บ1ไธญ่ฃก้ข้š”่‘—ๆœ€ๅคš0็š„้•ทๅบฆ ่งฃ้กŒๆ€่ทฏ ๅ…ˆๆ‰พๅ‡บbit 1็š„ไฝๅญ, ๅ†้–‹ๅง‹็ฎ—ไธญ้–“ๆœ€้•ท็š„้•ทๅบฆ ่งฃ้กŒๆ€่ทฏ้€šๅธธๅฏไปฅไฝฟ็”จไฝ้‹็ฎ—ไพ†่™•็†ไบŒ้€ฒๅˆถๆ•ธๅญ—ใ€‚ๆˆ‘ๅ€‘ๅฏไปฅๅฐ‡N่ฝ‰ๆ›็‚บไบŒ้€ฒๅˆถ่กจ็คบ๏ผŒ็„ถๅพŒไฝฟ็”จ้ๆญทๆˆ–่ฟดๅœˆไพ†ๆ‰พๅˆฐ็›ธ้„ฐ1ไน‹้–“็š„ๆœ€ๅคง่ท้›ขใ€‚ๅฏไปฅไฝฟ็”จๅ…ฉๅ€‹ๆŒ‡้‡ไพ†่จ˜้Œ„็›ธ้„ฐ็š„1็š„ ๆ™‚้–“่ค‡้›œๅบฆ: ่งฃ้กŒๆ€่ทฏไธญ็š„้ๆญทๆˆ–่ฟดๅœˆ้œ€่ฆๅฐ‡N่ฝ‰ๆ›็‚บไบŒ้€ฒๅˆถ๏ผŒๅ› ๆญคๆ™‚้–“่ค‡้›œๅบฆๅ–ๆฑบๆ–ผไบŒ้€ฒๅˆถ่กจ็คบ็š„ไฝๆ•ธใ€‚ๅ‡่จญN็š„ไฝๆ•ธ็‚บk๏ผŒๅ‰‡ๆ™‚้–“่ค‡้›œๅบฆ็‚บO(k)ใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ: ่งฃ้กŒๆ€่ทฏไธญไธ้œ€่ฆไฝฟ็”จ้กๅค–็š„ๆ•ธๆ“š็ตๆง‹๏ผŒๅช้œ€่ฆไฝฟ็”จๅนพๅ€‹่ฎŠๆ•ธไพ†ไฟๅญ˜ไฝ็ฝฎๅ’Œ่จˆ็ฎ—็ตๆžœ๏ผŒๅ› ๆญค็ฉบ้–“่ค‡้›œๅบฆ็‚บO(1)ใ€‚ ไพ†ๆบ https://app.codility.com/programmers/lessons/1-iterations/binary_gap/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0001.Iterations/Binary-Gap/Binary-Gap.go package binarygap // O(log n) func Solution(N int) int { maxLen, curLen := 0, 0 findOne := false for N > 0 { curBit := N & 1 if curBit == 1 { curLen = 0 findOne = true } else if curBit == 0 && findOne { curLen++ } if curLen > maxLen { maxLen = curLen } N = N >> 1 } return maxLen } // https://wandbox.org/permlink/totZwDAbL1wCgsqt func evil(x int) int { if x&(x+1) > 0 { return evil(x|(x>>1)) + 1 } else { return 0 } } func SolutionRecur(N int) int { for (N & 1) == 0 { N = N >> 1 } return evil(N) } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0002.Array/CyclicRotation/":{"url":"Codility/Lesson/0002.Array/CyclicRotation/","title":"Cyclic Rotation","summary":"Cyclic Rotation","keywords":"","body":"CyclicRotation tagsstart Codility Go Array Painless Multiple Pointers tagsstop An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7] (elements are shifted right by one index and 6 is moved to the first place). The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times. Write a function: func Solution(A []int, K int) []int that, given an array A consisting of N integers and an integer K, returns the array A rotated K times. For example, given A = [3, 8, 9, 7, 6] K = 3 the function should return [9, 7, 6, 3, 8]. Three rotations were made: [3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7] [6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9] [7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8] For another example, given A = [0, 0, 0] K = 1 the function should return [0, 0, 0] Given A = [1, 2, 3, 4] K = 4 the function should return [1, 2, 3, 4] Assume that: N and K are integers within the range [0..100]; each element of array A is an integer within the range [โˆ’1,000..1,000]. In your solution, focus on correctness. The performance of your solution will not be the focus of the assessment. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ CyclicRotation้กŒ็›ฎ่ฆๆฑ‚ๅฐ‡็ตฆๅฎš็š„ๆ•ดๆ•ธ้™ฃๅˆ—ๆŒ‰็…ง็ตฆๅฎš็š„ๆ—‹่ฝ‰ๆญฅๆ•ธ้€ฒ่กŒๅพช็’ฐๅณ็งป๏ผŒไธฆ่ฟ”ๅ›žๆ—‹่ฝ‰ๅพŒ็š„้™ฃๅˆ—ใ€‚ไพ‹ๅฆ‚๏ผŒๅฆ‚ๆžœ้™ฃๅˆ—ๆ˜ฏ[3, 8, 9, 7, 6]ไธ”ๆ—‹่ฝ‰ๆญฅๆ•ธๆ˜ฏ3๏ผŒๅ‰‡ๅณ็งปๅพŒ็š„้™ฃๅˆ—็‚บ[9, 7, 6, 3, 8]ใ€‚ ่งฃ้กŒๆ€่ทฏ ่งฃ้กŒๆ€่ทฏๅฏไปฅไฝฟ็”จๅคš็จฎๆ–นๆณ•ใ€‚ไธ€็จฎๅธธ่ฆ‹็š„ๆ–นๆณ•ๆ˜ฏไฝฟ็”จ้กๅค–็š„้™ฃๅˆ—ไพ†ๅญ˜ๅ„ฒๆ—‹่ฝ‰ๅพŒ็š„็ตๆžœใ€‚ๅฆไธ€็จฎๆ–นๆณ•ๆ˜ฏ้€š้Žๅพช็’ฐๅณ็งป็š„ๆ“ไฝœ๏ผŒ็›ดๆŽฅๅœจๅŽŸๅง‹้™ฃๅˆ—ไธŠ้€ฒ่กŒๅ…ƒ็ด ไบคๆ›ใ€‚ๆ นๆ“šๆ—‹่ฝ‰ๆญฅๆ•ธ๏ผŒๆˆ‘ๅ€‘ๅฏไปฅๅฐ‡้™ฃๅˆ—ๅˆ†็‚บๅ…ฉๅ€‹้ƒจๅˆ†๏ผŒไธฆ้€ฒ่กŒ็›ธๆ‡‰็š„ๅ…ƒ็ด ไบคๆ›ๆ“ไฝœใ€‚ ๆ™‚้–“่ค‡้›œๅบฆ: ่งฃ้กŒๆ€่ทฏไธญ็š„ๆ“ไฝœ้œ€่ฆ้ๆญทๆ•ดๅ€‹้™ฃๅˆ—๏ผŒๅ› ๆญคๆ™‚้–“่ค‡้›œๅบฆ็‚บO(N)๏ผŒๅ…ถไธญNๆ˜ฏ้™ฃๅˆ—็š„้•ทๅบฆใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ: ่งฃ้กŒๆ€่ทฏไธญไฝฟ็”จไบ†้กๅค–็š„้™ฃๅˆ—ๆˆ–้€ฒ่กŒๅŽŸๅœฐไบคๆ›๏ผŒไธ้œ€่ฆไฝฟ็”จ้กๅค–็š„ๆ•ธๆ“š็ตๆง‹๏ผŒๅ› ๆญค็ฉบ้–“่ค‡้›œๅบฆ็‚บO(1)ใ€‚ ไพ†ๆบ https://app.codility.com/programmers/lessons/2-arrays/cyclic_rotation/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0002.Array/CyclicRotation/CyclicRotation.go package cyclicrotation func Solution(A []int, K int) []int { if K == 0 || len(A) len(A) { K = K % len(A) } return append(A[len(A)-K:], A[:len(A)-K]...) } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0002.Array/OddOccurrencesInArray/":{"url":"Codility/Lesson/0002.Array/OddOccurrencesInArray/","title":"Odd Occurrences In Array","keywords":"","body":"OddOccurrencesInArray A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired. For example, in array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the elements at indexes 0 and 2 have value 9, the elements at indexes 1 and 3 have value 3, the elements at indexes 4 and 6 have value 9, the element at index 5 has value 7 and is unpaired. Write a function: func Solution(A []int) int that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element. For example, given array A such that: A[0] = 9 A[1] = 3 A[2] = 9 A[3] = 3 A[4] = 9 A[5] = 7 A[6] = 9 the function should return 7, as explained in the example above. Write an efficient algorithm for the following assumptions: N is an odd integer within the range [1..1,000,000]; each element of array A is an integer within the range [1..1,000,000,000]; all but one of the values in A occur an even number of times. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹้ž็ฉบarray A๏ผŒๅŒ…ๅซๆœ‰Nๅ€‹ๆ•ดๆ•ธ๏ผŒๆ‰พๅ‡บๅชๅ‡บ็พๅŸบๆ•ธๆฌก็š„ๆ•ดๅผ ่งฃ้กŒๆ€่ทฏ ๆ–นๆณ•ไธ€: ๅฏไปฅ็”จMap็ด€้Œ„ๆฏๅ€‹ๆ•ดๆ•ธๅ‡บ็พ็š„ๆฌกๆ•ธ, ๅœจๆชขๆŸฅๆ˜ฏๅฆๆ˜ฏๅถๆ•ธ ๆ–นๆณ•ไบŒ: ๆ‰€ๆœ‰็š„ๆ•ดๆ•ธXOR่ตทไพ†, ่‹ฅๆ˜ฏๅ…ฉๅ€‹ๆ•ดๆ•ธ็›ธๅŒXORๅพ—ๅˆฐ0, ๆœ€ๅพŒๅ‰ฉไธ‹ๅŸบๆ•ธๆฌก็š„ๆ•ธๅญ— ไพ†ๆบ https://app.codility.com/programmers/lessons/2-arrays/odd_occurrences_in_array/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0002.Array/OddOccurrencesInArray/OddOccurrencesInArray.go package oddoccurrencesinarray func Solution(A []int) int { intMap := make(map[int]int) for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0003.Time-Complexity/FrogJmp/":{"url":"Codility/Lesson/0003.Time-Complexity/FrogJmp/","title":"Frog Jmp","keywords":"","body":"FrogJmp A small frog wants to get to the other side of the road. The frog is currently located at position X and wants to get to a position greater than or equal to Y. The small frog always jumps a fixed distance, D. Count the minimal number of jumps that the small frog must perform to reach its target. Write a function: func Solution(X int, Y int, D int) int that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y. For example, given: X = 10 Y = 85 D = 30 the function should return 3, because the frog will be positioned as follows: after the first jump, at position 10 + 30 = 40 after the second jump, at position 10 + 30 + 30 = 70 after the third jump, at position 10 + 30 + 30 + 30 = 100 Write an efficient algorithm for the following assumptions: X, Y and D are integers within the range [1..1,000,000,000]; X โ‰ค Y. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://app.codility.com/programmers/lessons/3-time_complexity/frog_jmp/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0003.Time-Complexity/FrogJmp/FrogJmp.go package frogjump import ( \"math\" ) func Solution(X int, Y int, D int) int { if Y ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0003.Time-Complexity/PermMissingElem/":{"url":"Codility/Lesson/0003.Time-Complexity/PermMissingElem/","title":"Perm Missing Elem","keywords":"","body":"PermMissingElem An array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing. Your goal is to find that missing element. Write a function: func Solution(A []int) int that, given an array A, returns the value of the missing element. For example, given array A such that: A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5 the function should return 4, as it is the missing element. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; the elements of A are all distinct; each element of array A is an integer within the range [1..(N + 1)]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://app.codility.com/programmers/lessons/3-time_complexity/perm_missing_elem/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0003.Time-Complexity/PermMissingElem/PermMissingElem.go package permmissingelem func Solution(A []int) int { if len(A) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/":{"url":"Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/","title":"Tape Equilibrium","keywords":"","body":"TapeEquilibrium Minimize the value |(A[0] + ... + A[P-1]) - (A[P] + ... + A[N-1])|. A non-empty array A consisting of N integers is given. Array A represents numbers on a tape. Any integer P, such that 0 The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P โˆ’ 1]) โˆ’ (A[P] + A[P + 1] + ... + A[N โˆ’ 1])| In other words, it is the absolute difference between the sum of the first part and the sum of the second part. For example, consider array A such that: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 We can split this tape in four places: P = 1, difference = |3 โˆ’ 10| = 7 P = 2, difference = |4 โˆ’ 9| = 5 P = 3, difference = |6 โˆ’ 7| = 1 P = 4, difference = |10 โˆ’ 3| = 7 Write a function: func Solution(A []int) int that, given a non-empty array A of N integers, returns the minimal difference that can be achieved. For example, given: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 4 A[4] = 3 the function should return 1, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [2..100,000]; each element of array A is an integer within the range [โˆ’1,000..1,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://app.codility.com/programmers/lessons/3-time_complexity/tape_equilibrium/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/TapeEquilibrium.go package TapeEquilibrium import \"math\" func Solution(A []int) int { totalSum := 0 for _, v := range A { totalSum += v } leftSum := A[0] rightSum := totalSum - leftSum result := math.MaxInt32 for i := 1; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0004.Counting-Elements/FrogRiverOne/":{"url":"Codility/Lesson/0004.Counting-Elements/FrogRiverOne/","title":"Frog River One","keywords":"","body":"FrogRiverOne Find the earliest time when a frog can jump to the other side of a river. A small frog wants to get to the other side of a river. The frog is initially located on one bank of the river (position 0) and wants to get to the opposite bank (position X+1). Leaves fall from a tree onto the surface of the river. You are given an array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in seconds. The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X (that is, we want to find the earliest moment when all the positions from 1 to X are covered by leaves). You may assume that the speed of the current in the river is negligibly small, i.e. the leaves do not change their positions once they fall in the river. For example, you are given integer X = 5 and array A such that: A[0] = 1 A[1] = 3 A[2] = 1 A[3] = 4 A[4] = 2 A[5] = 3 A[6] = 5 A[7] = 4 In second 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river. Write a function: func Solution(X int, A []int) int that, given a non-empty array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river. If the frog is never able to jump to the other side of the river, the function should return โˆ’1. For example, given X = 5 and array A such that: A[0] = 1 A[1] = 3 A[2] = 1 A[3] = 4 A[4] = 2 A[5] = 3 A[6] = 5 A[7] = 4 the function should return 6, as explained above. Write an efficient algorithm for the following assumptions: N and X are integers within the range [1..100,000]; each element of array A is an integer within the range [1..X]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่ฆXๆญฅๆ‰่ƒฝๅˆฐๅฐ้ข, ๆฏไธ€ๅ€‹่ตฐ้Ž็š„ไฝๅญไธ่ƒฝ้‡่ค‡่จˆ็ฎ— ่งฃ้กŒๆ€่ทฏ ไฝฟ็”จmapๅญ˜ๅ“ชไบ›ๅœฐๆ–น่ตฐ้Ž ไพ†ๆบ https://app.codility.com/programmers/lessons/4-counting_elements/frog_river_one/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/FrogRiverOne.go package FrogRiverOne func Solution(X int, A []int) int { intMap := make(map[int]bool) for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0004.Counting-Elements/MaxCounters/":{"url":"Codility/Lesson/0004.Counting-Elements/MaxCounters/","title":"Max Counters","keywords":"","body":"MaxCounters Calculate the values of counters after applying all alternating operations: increase counter by 1; set value of all counters to current maximum. You are given N counters, initially set to 0, and you have two possible operations on them: increase(X) โˆ’ counter X is increased by 1, max counter โˆ’ all counters are set to the maximum value of any counter. A non-empty array A of M integers is given. This array represents consecutive operations: if A[K] = X, such that 1 โ‰ค X โ‰ค N, then operation K is increase(X), if A[K] = N + 1 then operation K is max counter. For example, given integer N = 5 and array A such that: A[0] = 3 A[1] = 4 A[2] = 4 A[3] = 6 A[4] = 1 A[5] = 4 A[6] = 4 the values of the counters after each consecutive operation will be: (0, 0, 1, 0, 0) (0, 0, 1, 1, 0) (0, 0, 1, 2, 0) (2, 2, 2, 2, 2) (3, 2, 2, 2, 2) (3, 2, 2, 3, 2) (3, 2, 2, 4, 2) The goal is to calculate the value of every counter after all operations. Write a function: func Solution(N int, A []int) []int that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters. Result array should be returned as an array of integers. For example, given: A[0] = 3 A[1] = 4 A[2] = 4 A[3] = 6 A[4] = 1 A[5] = 4 A[6] = 4 the function should return [3, 2, 2, 4, 2], as explained above. Write an efficient algorithm for the following assumptions: N and M are integers within the range [1..100,000]; each element of array A is an integer within the range [1..N + 1]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๅฆ‚ๆžœA[i] ๅฐๆ–ผ N ๅ‰‡ๅฐ‡่จˆๆ•ธๅ™จไธญๅฐๆ‡‰ไฝ็ฝฎ็š„ๆ•ธ+1, ๅฆ‚ๆžœA[i] ๅคงๆ–ผ N ๅ‰‡ๅฐ‡่จˆๆ•ธๅ™จไธญๆ‰€ๆœ‰็š„ๆ•ธๆ›ดๆ–ฐ็‚บ่จˆๆ•ธๅ™จ็•ถๅ‰็š„ๆœ€ๅคงๆ•ธๅ€ผ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://app.codility.com/programmers/lessons/4-counting_elements/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/MaxCounters/MaxCounters.go package MaxCounters func Max(x, y int) int { if x > y { return x } return y } // ๆ™‚้–“ O(N+M) , ็ฉบ้–“ O(N) func Solution(N int, A []int) []int { result := make([]int, N) maxNum := 0 nowMaxNum := 0 for i := 0; i N { // ๅฆ‚ๆžœA[i] ๅคงๆ–ผ N ๅ‰‡ๅฐ‡่จˆๆ•ธๅ™จไธญๆ‰€ๆœ‰็š„ๆ•ธๆ›ดๆ–ฐ็‚บ่จˆๆ•ธๅ™จ็•ถๅ‰็š„ๆœ€ๅคงๆ•ธๅ€ผ maxNum = nowMaxNum } else { // ๅฆ‚ๆžœA[i] ๅฐๆ–ผ N ๅ‰‡ๅฐ‡่จˆๆ•ธๅ™จไธญๅฐๆ‡‰ไฝ็ฝฎ็š„ๆ•ธ+1, if result[A[i]-1] ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0004.Counting-Elements/MissingInteger/":{"url":"Codility/Lesson/0004.Counting-Elements/MissingInteger/","title":"Missing Integer","keywords":"","body":"MissingInteger Find the smallest positive integer that does not occur in a given sequence. This is a demo task. Write a function: func Solution(A []int) int that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [โˆ’1, โˆ’3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [โˆ’1,000,000..1,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆ‰พๅ‡บ่ฉฒarrayๆฒ’ๅ‡บ็พ็š„ๆœ€ๅฐๆ•ดๆ•ธ ่งฃ้กŒๆ€่ทฏ ๅ…ˆ่ฌ›ๅ‡บ็พ็š„ๆ•ธๅญ—่จ˜้Œ„่ตทไพ†, ๅ†ไพๅบๅพž1้–‹ๅง‹ๅพ€ๅพŒๆ‰พๅ‡บๆœ€ๅฐ็š„ๆ•ดๆ•ธไธ”ๆฒ’ๅ‡บ็พ้Ž ไพ†ๆบ https://app.codility.com/programmers/lessons/4-counting_elements/missing_integer/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/MissingInteger/MissingInteger.go package MissingInteger func Solution(A []int) int { smallNum := 1 intMap := make(map[int]bool) // ๅฐ‡ๅ‡บ็พ็š„ๆ•ธๅญ—ๅกžๅ…ฅmap for _, v := range A { if v > 0 && !intMap[v] { intMap[v] = true } } for i := 1; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0004.Counting-Elements/PermCheck/":{"url":"Codility/Lesson/0004.Counting-Elements/PermCheck/","title":"Perm Check","keywords":"","body":"PermCheck Check whether array A is a permutation. A non-empty array A consisting of N integers is given. A permutation(ๆŽ’ๅˆ—) is a sequence containing each element from 1 to N once, and only once. For example, array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 is a permutation, but array A such that: A[0] = 4 A[1] = 1 A[2] = 3 is not a permutation, because value 2 is missing. The goal is to check whether array A is a permutation. Write a function: func Solution(A []int) int that, given an array A, returns 1 if array A is a permutation and 0 if it is not. For example, given array A such that: A[0] = 4 A[1] = 1 A[2] = 3 A[3] = 2 the function should return 1. Given array A such that: A[0] = 4 A[1] = 1 A[2] = 3 the function should return 0. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [1..1,000,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๅฆ‚ๆžœๆ˜ฏ้€ฃ็บŒๆŽ’ๅˆ—็š„array ๅ›žๅ‚ณ 1 ๅไน‹ๅ›žๅ‚ณ1 ่งฃ้กŒๆ€่ทฏ ้กžไผผlesson 4็š„MissingInteger. ๅ…ˆๅฐ‡็พๆœ‰็š„็›ดๅฏซๅ…ฅๅˆฐmap. ้™คไบ†ๆชขๆŸฅๆ˜ฏๅฆๆœ‰้‡่ค‡ๆ•ธๅญ—ๅ‡บ็พๅค–,้ †ไพฟๅฐ‡็ธฝๅ’Œ็ฎ—่ตทไพ† ๆœ€ๅพŒๆชขๆŸฅ็ธฝๆ™‚ๅฐไธๅฐ ไพ†ๆบ https://app.codility.com/programmers/lessons/4-counting_elements/perm_check/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0004.Counting-Elements/PermCheck/PermCheck.go package PermCheck func Solution(A []int) int { intMap := make(map[int]bool) for _, v := range A { if !intMap[v] { intMap[v] = true } else { // ้‡่ค‡ๅ‡บ็พ return 0 } } for i := 1; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0005.Prefix-Sums/CountDiv/":{"url":"Codility/Lesson/0005.Prefix-Sums/CountDiv/","title":"Count Div","keywords":"","body":"CountDiv Compute number of integers divisible by k in range [a..b]. Write a function: func Solution(A int, B int, K int) int that, given three integers A, B and K, returns the number of integers within the range [A..B] that are divisible by K, i.e.: { i : A โ‰ค i โ‰ค B, i mod K = 0 } For example, for A = 6, B = 11 and K = 2, your function should return 3, because there are three numbers divisible by 2 within the range [6..11], namely 6, 8 and 10. Write an efficient algorithm for the following assumptions: A and B are integers within the range [0..2,000,000,000]; K is an integer within the range [1..2,000,000,000]; A โ‰ค B. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ A~Bไน‹้–“็š„ๆ•ธๅญ— mod K ๅพŒ็‚บ0 ็š„ๆ•ธๅญ—ๆœ‰ๅนพๅ€‹ ่งฃ้กŒๆ€่ทฏ B/K ๆ‰พๅ‡บๆœ€ๅคง็š„ๅ•†, A/K ๆœ€ๅฐ็š„ๅ•†. ็›ธๆธ›ๅ–ๅพ—ๅœจๆญคไธญ้–“ไน‹ๅ•†็š„ๆ•ธ้‡. ๅฆ‚ๆžœA%K==0 ้œ€่ฆๅœจ+1 ไพ†ๆบ https://app.codility.com/programmers/lessons/5-prefix_sums/count_div/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/CountDiv/CountDiv.go package CountDiv import \"math\" // ๆ™‚้–“: O(n) func SolutionBurst(A int, B int, K int) int { result := 0 for i := A; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/":{"url":"Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/","title":"Genomic Range Query","keywords":"","body":"GenomicRangeQuery Find the minimal nucleotide(ๆ ธ่‹ท้…ธ) from a range of sequence DNA. A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which correspond to the types of successive nucleotides in the sequence. Each nucleotide has an impact factor, which is an integer. Nucleotides of types A, C, G and T have impact factors of 1, 2, 3 and 4, respectively. You are going to answer several queries of the form: What is the minimal impact factor of nucleotides contained in a particular part of the given DNA sequence? The DNA sequence is given as a non-empty string S = S[0]S[1]...S[N-1] consisting of N characters. There are M queries, which are given in non-empty arrays P and Q, each consisting of M integers. The K-th query (0 โ‰ค K For example, consider string S = CAGCCTA and arrays P, Q such that: P[0] = 2 Q[0] = 4 P[1] = 5 Q[1] = 5 P[2] = 0 Q[2] = 6 The answers to these M = 3 queries are as follows: The part of the DNA between positions 2 and 4 contains nucleotides G and C (twice), whose impact factors are 3 and 2 respectively, so the answer is 2. The part between positions 5 and 5 contains a single nucleotide T, whose impact factor is 4, so the answer is 4. The part between positions 0 and 6 (the whole string) contains all nucleotides, in particular nucleotide A whose impact factor is 1, so the answer is 1. Write a function: func Solution(S string, P []int, Q []int) []int that, given a non-empty string S consisting of N characters and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M integers specifying the consecutive answers to all queries. Result array should be returned as an array of integers. For example, given the string S = CAGCCTA and arrays P, Q such that: P[0] = 2 Q[0] = 4 P[1] = 5 Q[1] = 5 P[2] = 0 Q[2] = 6 the function should return the values [2, 4, 1], as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; M is an integer within the range [1..50,000]; each element of arrays P, Q is an integer within the range [0..N โˆ’ 1]; P[K] โ‰ค Q[K], where 0 โ‰ค K ้กŒ็›ฎๅคงๆ„ CAGCCTA A ไปฃ่กจ1, C ไปฃ่กจ2, G ไปฃ่กจ3 ,T ไปฃ่กจ4 K=0: P[0]=2, Q[0]=4 ไน‹้–“็š„ๆ ธ่‹ท้…ธ DNA(GCC)ๅ› ็ด ๅˆ†ๅˆฅๆ˜ฏ3ๅ’Œ2, ๆœ€ๅฐ็š„ๅฐฑๆ˜ฏ2. K=1: P[1]=5, Q[1]=5 DNA(T),ๆœ€ๅฐ็š„ๆ˜ฏ4. K=2: P[2]=0, Q[2]=6 DNA(CAGCCTA),ๆœ€ๅฐ็š„ๆ˜ฏ1. ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://app.codility.com/programmers/lessons/5-prefix_sums/genomic_range_query/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/GenomicRangeQuery.go package GenomicRangeQuery func Solution(S string, P []int, Q []int) []int { A, C, G, T := prefixSums(S) result := make([]int, len(P)) /* // fmt.Println(\"A: \", A) // fmt.Println(\"C: \", C) // fmt.Println(\"G: \", G) // fmt.Println(\"T: \", T) idx 0 1 2 3 4 5 6 7 S: [C A G C C T A] A: [0 0 1 1 1 1 1 2] C: [0 1 1 1 2 3 3 3] G: [0 0 0 1 1 1 1 1] T: [0 0 0 0 0 0 1 1] P: [2 5 0] Q: [4 5 6] */ for k, _ := range P { // ๅˆคๆ–ท A[end of slice]-A[Begin of Slice]ๆ˜ฏๅฆๅคงๆ–ผ้›ถ ๅณๅฏๅˆคๆ–ทๆ˜ฏๅฆ A ๅ‡บ็พ้Ž if A[Q[k]+1]-A[P[k]] > 0 { result[k] = 1 } else if C[Q[k]+1]-C[P[k]] > 0 { result[k] = 2 } else if G[Q[k]+1]-G[P[k]] > 0 { result[k] = 3 } else if T[Q[k]+1]-T[P[k]] > 0 { result[k] = 4 } } return result } // ๆ•ธ็ฎ—ๅพž้–‹ๅง‹ๅˆฐๆฏๅ€‹ๅ›บๅฎš็ดขๅผ•็š„A,C,G,Tๅ€‹ๆ•ธ. ้–‹้ ญๆ’ๅ…ฅ0 func prefixSums(S string) ([]int, []int, []int, []int) { n := len(S) A := make([]int, n+1) C := make([]int, n+1) G := make([]int, n+1) T := make([]int, n+1) for i := 1; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/":{"url":"Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/","title":"Min Avg Two Slice","keywords":"","body":"MinAvgTwoSlice Find the minimal average of any slice containing at least two elements. A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 โ‰ค P For example, array A such that: A[0] = 4 A[1] = 2 A[2] = 2 A[3] = 5 A[4] = 1 A[5] = 5 A[6] = 8 contains the following example slices: slice (1, 2), whose average is (2 + 2) / 2 = 2; slice (3, 4), whose average is (5 + 1) / 2 = 3; slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5. The goal is to find the starting position of a slice whose average is minimal. Write a function: func Solution(A []int) int that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice. For example, given array A such that: A[0] = 4 A[1] = 2 A[2] = 2 A[3] = 5 A[4] = 1 A[5] = 5 A[6] = 8 the function should return 1, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [2..100,000]; each element of array A is an integer within the range [โˆ’10,000..10,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆ‰พๅ‡บarrayๅ…ฉindexไธญๅนณๅ‡ๅ€ผๆœ€ๅฐ ,ไธฆๅ›žๅ‚ณstart็š„ index ่งฃ้กŒๆ€่ทฏ ๆœ€ๅฐavg็š„slice(n,m)๏ผŒm-n+1ไธ€ๅฎšๆ˜ฏ2ๆˆ–่€…3๏ผŒไนŸๅฐฑๆ˜ฏ้€™ๅ€‹ๆœ€ๅฐavg็š„slice็”ฑ2ๅ€‹ๆˆ–่€…3ๅ€‹ๅ…ƒ็ด ็ต„ๆˆ ๅ› ็‚บ้กŒ็›ฎไธญ่ชชๆ˜Ž 0 ๅ› ๆญคๅฏไปฅๅพ—ๅ‡บ2ๅ€‹ๆˆ–่€…3ๅ€‹ๅ…ƒ็ด ๆ˜ฏๆœ€ๅฐ็š„็ต„ๅˆ๏ผŒๆฏ”ๅฆ‚length=3็š„ๆ•ธ็ต„๏ผŒไฝ ็„กๆณ•ไธ€ๆฌกๅˆ†ๅ‡บ2ๅ€‹slice๏ผŒlength=2็š„ๆ•ธ็ต„ไนŸไธ€ๆจฃใ€‚็‚บไป€้บผ่ฆ้€™้บผๅŽปๆƒณๅ‘ข๏ผŸๅ› ็‚บไฝ ่ฆโ€œๆฏ”่ผƒโ€ๅ‡บๆœ€ๅฐ็š„avg๏ผŒๆ€Ž้บผๆ‰่ƒฝ\"ๆฏ”่ผƒ\"๏ผŸ้‚ฃๅฐฑๆ˜ฏๅฟ…้ ˆไธ€ๆฌก่‡ณๅฐ‘ๆœ‰2ๅ€‹sliceๆ‰่ƒฝ็›ธไบ’ๆฏ”่ผƒใ€‚้‚ฃ้บผ็•ถN>=4ๆ™‚๏ผŒๆˆ‘ๅ€‘ๅฐฑ่ƒฝไธ€ๆฌกๆœ€ๅฐ‘ๅˆ†ๅ‡บ2ๅ€‹slice ไพ†ๆบ https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/ https://blog.csdn.net/dear0607/article/details/42581149 ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/MinAvgTwoSlice.go package MinAvgTwoSlice import \"math\" func Solution(A []int) int { min := math.MaxFloat64 minIndex := -1 for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0005.Prefix-Sums/PassingCars/":{"url":"Codility/Lesson/0005.Prefix-Sums/PassingCars/","title":"Passing Cars","keywords":"","body":"PassingCars A non-empty array A consisting of N integers is given. The consecutive(้€ฃ็บŒ) elements of array A represent consecutive cars on a road. Array A contains only 0s and/or 1s: 0 represents a car traveling east, 1 represents a car traveling west. The goal is to count passing cars. We say that a pair of cars (P, Q), where 0 โ‰ค P For example, consider array A such that: A[0] = 0 // no.0 car trave to east A[1] = 1 // no.1 car trave to west A[2] = 0 // no.2 car trave to east A[3] = 1 // no.3 car trave to west A[4] = 1 // no.4 car trave to west We have five pairs of passing cars: (0, 1), (0, 3), (0, 4), (2, 3), (2, 4). Write a function: func Solution(A []int) int that, given a non-empty array A of N integers, returns the number of pairs of passing cars. The function should return โˆ’1 if the number of pairs of passing cars exceeds 1,000,000,000. For example, given: A[0] = 0 A[1] = 1 A[2] = 0 A[3] = 1 A[4] = 1 the function should return 5, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer that can have one of the following values: 0, 1. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆฏๅฐ่ปŠ็š„่ปŠ่™Ÿ็‚บA[]็š„index, 0 ไปฃ่กจๅพ€ๆฑ, 1ไปฃ่กจๅพ€่ฅฟ, ๅ‘ๆฑ็š„่ปŠ่™Ÿ้œ€่ฆๅฐๆ–ผๅ‘่ฅฟ็š„่ปŠ่™Ÿ. ๆ‰พๅ‡บๆœƒ่ปŠ็š„ๅนพ็จฎๅฏ่ƒฝๆ€ง ่งฃ้กŒๆ€่ทฏ ๆฏไธ€ๅ€‹ๅ‘ๆฑ่ตฐ็š„่ปŠ, ้ƒฝๆœƒ่ทŸๅ‘่ฅฟ็š„้…ๅฐ. ็•ถ้‡ๅˆฐๅ‘่ฅฟๆ™‚็ต„ๅˆ+1. ๆ‰€ไปฅ่ปŠ่™Ÿ0ๅฏไปฅ่ทŸๆ‰€ๆœ‰ๅคงๆ–ผ0็š„ๅ‘่ฅฟ่ปŠ้…ๅฐ. ่ปŠ่™Ÿ2่ทŸๆ‰€ๆœ‰ๅคงๆ–ผ0็š„ๅ‘่ฅฟ่ปŠ้…ๅฐ 1่™Ÿ่ปŠๅ‰้ขๅชๆœ‰่ปŠ่™Ÿ0้€™้ธๆ“‡. ่ปŠ่™Ÿ3่ทŸ4ๆœ‰่ปŠ่™Ÿ0่ทŸ2้€™ๅ…ฉๅ€‹้ธๆ“‡. ๆ‰€ไปฅๆ˜ฏ1+2*2=5 ไพ†ๆบ https://app.codility.com/programmers/lessons/5-prefix_sums/passing_cars/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0005.Prefix-Sums/PassingCars/PassingCars.go package PassingCars func Solution(A []int) int { addBase, result := 0, 0 for i := 0; i 1000000000 { return -1 } return result } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0006.Sorting/Distinct/":{"url":"Codility/Lesson/0006.Sorting/Distinct/","title":"Distinct","keywords":"","body":"Distinct Compute number of distinct values in an array. Write a function func Solution(A []int) int that, given an array A consisting of N integers, returns the number of distinct values in array A. For example, given array A consisting of six elements such that: A[0] = 2 A[1] = 1 A[2] = 1 A[3] = 2 A[4] = 3 A[5] = 1 the function should return 3, because there are 3 distinct values appearing in array A, namely 1, 2 and 3. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [โˆ’1,000,000..1,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่ฟ”ๅ›žไธ้‡่ค‡็š„ๆ•ดๆ•ธๆ•ธ้‡ ่งฃ้กŒๆ€่ทฏ ๆ–นๆณ•ใ„ง: ๅ…ˆๆŽ’ๅบ, ๅœจๆชขๆŸฅ็•ถๅ‰่ทŸๅ‰ไธ€ๅ€‹ๆ˜ฏไธๆ˜ฏๅŒไธ€ๅ€‹ๆ•ดๆ•ธ. ไธๆ˜ฏ็š„ๆœƒ็ตๆžœ+1 ๆ–นๆณ•ไบŒ: ๅปบ็ซ‹ไธ€ๅ€‹set. ๆœ€ๅพŒ่ฟ”ๅ›žset็š„้•ทๅบฆ ไพ†ๆบ https://app.codility.com/programmers/lessons/6-sorting/distinct/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/Distinct/Distinct.go package Distinct import \"sort\" func Solution(A []int) int { sort.Ints(A) if len(A) == 0 { return 0 } result := 1 for i := 1; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0006.Sorting/MaxProductOfThree/":{"url":"Codility/Lesson/0006.Sorting/MaxProductOfThree/","title":"Max Product Of Three","keywords":"","body":"MaxProductOfThree Maximize A[P] A[Q] A[R] for any triplet (P, Q, R). A non-empty array A consisting of N integers is given. The product of triplet (P, Q, R) equates to A[P] A[Q] A[R] (0 โ‰ค P For example, array A such that: A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 contains the following example triplets: (0, 1, 2), product is โˆ’3 1 2 = โˆ’6 (1, 2, 4), product is 1 2 5 = 10 (2, 4, 5), product is 2 5 6 = 60 Your goal is to find the maximal product of any triplet. Write a function: func Solution(A []int) int that, given a non-empty array A, returns the value of the maximal product of any triplet. For example, given array A such that: A[0] = -3 A[1] = 1 A[2] = 2 A[3] = -2 A[4] = 5 A[5] = 6 the function should return 60, as the product of triplet (2, 4, 5) is maximal. Write an efficient algorithm for the following assumptions: N is an integer within the range [3..100,000]; each element of array A is an integer within the range [โˆ’1,000..1,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ็ตฆไธ€ๆ•ดๆ•ธ้™ฃๅˆ—A๏ผŒๆ‰พๅ‡บ้™ฃๅˆ—ไธญไปปๆ„ไธ‰ๆ•ธไน˜็ฉ็š„ๆœ€ๅคงๅ€ผ ่งฃ้กŒๆ€่ทฏ ๅ…ˆๆŽ’ๅบ.็„ถๅพŒๆฏ”่ผƒ ๅ‰ๅ…ฉๅ€‹ๅ…ƒ็ด *ๆœ€ๅพŒไธ€ๅ€‹ๅ…ƒ็ด ็š„ไน˜็ฉ ๅ’Œ ๆœ€ๅพŒไธ‰ๅ€‹ๅ…ƒ็ด ็š„ไน˜็ฉ ๅ–ๆœ€ๅคงๅ€ผ ไพ†ๆบ https://app.codility.com/programmers/lessons/6-sorting/max_product_of_three/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/MaxProductOfThree/MaxProductOfThree.go package MaxProductOfThree import \"sort\" func max(a, b int) int { if a > b { return a } return b } func Solution(A []int) int { sort.Ints(A) aLen := len(A) return max(A[0]*A[1]*A[aLen-1], A[aLen-1]*A[aLen-2]*A[aLen-3]) } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/":{"url":"Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/","title":"Number Of Disc Intersections","keywords":"","body":"NumberOfDiscIntersections Compute the number of intersections(็›ธไบค) in a sequence of discs(ๅœ“็›ค). We draw N discs on a plane. The discs are numbered from 0 to N โˆ’ 1. An array A of N non-negative integers, specifying the radiuses(ๅŠๅพ‘) of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J]. We say that the J-th disc and K-th disc intersect if J โ‰  K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders). The figure below shows discs drawn for N = 6 and A as follows: A[0] = 1 A[1] = 5 A[2] = 2 A[3] = 1 A[4] = 4 A[5] = 0 There are eleven (unordered) pairs of discs that intersect, namely: discs 1 and 4 intersect, and both intersect with all the other discs; disc 2 also intersects with discs 0 and 3. Write a function: func Solution(A []int) int that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return โˆ’1 if the number of intersecting pairs exceeds 10,000,000. Given array A shown above, the function should return 11, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [0..2,147,483,647]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ A[0] = 1, ไปฃ่กจๅœจ(0,0)็š„ไฝ็ฝฎไธŠๆœ‰ไธ€ๅ€‹ๅŠๅพ‘็‚บ1็š„ๅœ“. ๆ‰พๅ‡บๅœ“็›ธไบค็š„ๅ€‹ๆ•ธ ่งฃ้กŒๆ€่ทฏ ๆ–นๆณ•ไธ€: ๅฐๆ–ผ็ฌฌi๏ผŒjๅ€‹ๅœ“ไพ†่ชช๏ผŒๅฆ‚ๆžœๅ…ฉๅ€‹ๅŽŸ่ฆ็›ธไบค็š„่ฉฑ ๅƒ่€ƒSolutionDirect. ๆ™‚้–“่ค‡้›œๅบฆ็‚บO(n^2) ๆ–นๆณ•ไบŒ ไนŸๅฐฑๆ˜ฏๅฐ‡ๅŽŸไพ†็š„ไบŒ็ถญ็š„็ทšๆฎตๅˆ—่กจ่ฎŠ็‚บ2ๅ€‹ไธ€็ถญ็š„ๅˆ—่กจ ้ฆ–ๅ…ˆ้ๆญทๆ•ธ็ต„Aๅพ—ๅˆฐA[i]+i็ต„ๆˆ็š„ๆ•ธ็ต„i_limit๏ผŒไปฅๅŠj-A[j]็ต„ๆˆ็š„ๆ•ธ็ต„j_limitใ€‚็„ถๅพŒๅ†้ๆญทๆ•ธ็ต„i_limitไธญ็š„ๅ…ƒ็ด S๏ผŒๅˆฉ็”จไบŒๅˆ†ๆŸฅๆ‰พ็ฎ—ๆณ•ๅพ—ๅˆฐๆ•ธ็ต„j_limitไธญไธๅคงๆ–ผS็š„ๅ…ƒ็ด ๅ€‹ๆ•ธใ€‚ๅ‰ไธ€ๅ€‹ๆ“ไฝœๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏO(N)๏ผŒไบŒๅˆ†ๆŸฅๆ‰พ็ฎ—ๆณ•ๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏO(LogN)๏ผŒๅ› ๆญคๆœ€็ต‚็š„ๆ™‚้–“่ค‡้›œๅบฆ็‚บO(N*logN)ใ€‚ๅƒ่€ƒSolutionใ€‚ ไพ†ๆบ https://app.codility.com/programmers/lessons/6-sorting/number_of_disc_intersections/ https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L6_Sorting/6.4%20NumberOfDiscIntersections.md https://rafal.io/posts/codility-intersecting-discs.html https://github.com/tmpapageorgiou/algorithm/blob/master/number_disc_intersections.py ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/NumberOfDiscIntersections.go package NumberOfDiscIntersections import \"sort\" func max(a, b int) int { if a > b { return a } return b } func min(a, b int) int { if a > b { return b } return a } // ๆ™‚้–“่ค‡้›œ O(n^2) func SolutionDirect(A []int) int { count := 0 for indexI, valueI := range A { tmpArr := A[indexI+1:] for indexJ, valueJ := range tmpArr { if valueI+valueJ >= indexJ+indexI+1-indexI { count++ } } } return count } // ๆ™‚้–“่ค‡้›œ O(nlogn) or O(n) // TODO: ๅพ…็ ”็ฉถ func Solution(A []int) int { iLimit := make([]int, len(A)) // ๅทฆ jLimit := make([]int, len(A)) // ๅณ result := 0 for i := 0; i end }) // ๅ› ็‚บi=jๆ™‚๏ผŒA[i]+i ่‚ฏๅฎšไธๅฐๆ–ผj-A[j],ไนŸๅฐฑๆ˜ฏ่ชชๅคš็ฎ—ไบ†ไธ€ๅ€‹๏ผŒๅ› ๆญค่ฆๆธ›ๅŽป1ใ€‚ // ๆธ›ๅŽปidxๆ˜ฏๅ› ็‚บๅœ“็›คAๅ’Œๅœ“็›คB็›ธไบค๏ผŒๆฌกๆ•ธๅŠ ไธŠ1ไบ†๏ผŒๅœ“็›คBๅ’Œๅœ“็›คA็›ธไบคๅฐฑไธ็”จๅ†ๅŠ 1ไบ†ใ€‚ count = count - idx - 1 result += count if result > 10000000 { return -1 } } return result } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0006.Sorting/Triangle/":{"url":"Codility/Lesson/0006.Sorting/Triangle/","title":"Triangle","keywords":"","body":"Triangle Determine whether a triangle can be built from a given set of edges. An array A consisting of N integers is given. A triplet (P, Q, R) is triangular if 0 โ‰ค P A[P] + A[Q] > A[R], A[Q] + A[R] > A[P], A[R] + A[P] > A[Q]. For example, consider array A such that: A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20 Triplet (0, 2, 4) is triangular. Write a function: func Solution(A []int) int that, given an array A consisting of N integers, returns 1 if there exists a triangular triplet for this array and returns 0 otherwise. For example, given array A such that: A[0] = 10 A[1] = 2 A[2] = 5 A[3] = 1 A[4] = 8 A[5] = 20 the function should return 1, as explained above. Given array A such that: A[0] = 10 A[1] = 50 A[2] = 5 A[3] = 1 the function should return 0. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [โˆ’2,147,483,648..2,147,483,647]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๅฆ‚ๆžœ่ฉฒarrayๅญ˜ๅœจไธ€ๅ€‹ไธ‰่ง’ๅฝข็š„ไธ‰ๅ…ƒ็ต„,ๅ‰‡่ฟ”ๅ›ž1, ๅฆๅ‰‡่ฟ”ๅ›ž0 ่งฃ้กŒๆ€่ทฏ ๅพžๅคงๅˆฐๅฐๆŽ’ๅบ, ๅฆ‚ๆžœๅ‰้ข็š„ๅ€ผๅฐๆ–ผๅพŒ้ขๅ…ฉๆ•ธๅ’Œ, ๅ‰‡ๅฏไปฅ็ต„ๆˆไธ‰่ง’ๅฝข. ไธ‰ๆ•ธ็š†ไธ่ƒฝ็‚บ0ๆˆ–่ฒ ๆ•ธ ไพ†ๆบ https://app.codility.com/programmers/lessons/6-sorting/triangle/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0006.Sorting/Triangle/Triangle.go package Triangle import \"sort\" func Solution(A []int) int { if len(A) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0007.Stacks-and-Queues/Brackets/":{"url":"Codility/Lesson/0007.Stacks-and-Queues/Brackets/","title":"Brackets","keywords":"","body":"Brackets Determine whether a given string of parentheses (multiple types) is properly nested. A string S consisting of N characters is considered to be properly nested if any of the following conditions is true: S is empty; S has the form \"(U)\" or \"[U]\" or \"{U}\" where U is a properly nested string; S has the form \"VW\" where V and W are properly nested strings. For example, the string \"{[()()]}\" is properly nested but \"([)()]\" is not. Write a function: func Solution(S string) int that, given a string S consisting of N characters, returns 1 if S is properly nested and 0 otherwise. For example, given S = \"{[()()]}\", the function should return 1 and given S = \"([)()]\", the function should return 0, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..200,000]; string S consists only of the following characters: \"(\", \"{\", \"[\", \"]\", \"}\" and/or \")\". Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆ‹ฌ่™Ÿ้…ๅฐ, ๅฏ้…ๅฐๅ›žๅ‚ณ1 ๅไน‹ๅ›žๅ‚ณ0. ่งฃ้กŒๆ€่ทฏ ๅฐ‡ๅทฆๆ‹ฌ่™Ÿ้ƒฝๆ”พๅ…ฅstack. ้‡ๅˆฐๅณๆ‹ฌ่™Ÿๆ™‚ๅฐ‡stack popๅ‡บไพ†ไธฆๆชขๆŸฅpopๅ‡บไพ†็š„ๅทฆๆ‹ฌ่™Ÿๆ˜ฏๅฆ่ทŸๅณๆ‹ฌ่™Ÿ้…ๅฐ. ไพ†ๆบ https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/Brackets/Brackets.go package Brackets import ( \"LeetcodeGolang/Utility/structures\" ) func Solution(S string) int { if len(S) == 0 { return 1 } if len(S)%2 != 0 { return 0 } BracketMap := map[string]string{ \")\": \"(\", \"]\": \"[\", \"}\": \"{\", } stack := structures.NewArrayStack() for _, v := range S { val := string(v) if val == \"(\" || val == \"[\" || val == \"{\" { stack.Push(val) } else if val == \")\" || val == \"]\" || val == \"}\" { if stack.IsEmpty() { return 0 } topVal := stack.Top() if topVal == BracketMap[val] { stack.Pop() } else { // ๆ‰พไธๅˆฐๅฏ้…ๅฐ็š„ๆ‹ฌ่™Ÿ return 0 } } } if stack.IsEmpty() { return 1 } else { return 0 } } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0007.Stacks-and-Queues/Fish/":{"url":"Codility/Lesson/0007.Stacks-and-Queues/Fish/","title":"Fish","keywords":"","body":"Fish N voracious fish are moving along a river. Calculate how many fish are alive. You are given two non-empty arrays A and B consisting of N integers. Arrays A and B represent N voracious fish in a river, ordered downstream along the flow of the river. The fish are numbered from 0 to N โˆ’ 1. If P and Q are two fish and P Fish number P is represented by A[P] and B[P]. Array A contains the sizes of the fish. All its elements are unique. Array B contains the directions of the fish. It contains only 0s and/or 1s, where: 0 represents a fish flowing upstream, 1 represents a fish flowing downstream. If two fish move in opposite directions and there are no other (living) fish between them, they will eventually meet each other. Then only one fish can stay alive โˆ’ the larger fish eats the smaller one. More precisely, we say that two fish P and Q meet each other when P If A[P] > A[Q] then P eats Q, and P will still be flowing downstream, If A[Q] > A[P] then Q eats P, and Q will still be flowing upstream. We assume that all the fish are flowing at the same speed. That is, fish moving in the same direction never meet. The goal is to calculate the number of fish that will stay alive. For example, consider arrays A and B such that: A[0] = 4 B[0] = 0 A[1] = 3 B[1] = 1 A[2] = 2 B[2] = 0 A[3] = 1 B[3] = 0 A[4] = 5 B[4] = 0 Initially all the fish are alive and all except fish number 1 are moving upstream. Fish number 1 meets fish number 2 and eats it, then it meets fish number 3 and eats it too. Finally, it meets fish number 4 and is eaten by it. The remaining two fish, number 0 and 4, never meet and therefore stay alive. Write a function: func Solution(A []int, B []int) int that, given two non-empty arrays A and B consisting of N integers, returns the number of fish that will stay alive. For example, given the arrays shown above, the function should return 2, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [0..1,000,000,000]; each element of array B is an integer that can have one of the following values: 0, 1; the elements of A are all distinct. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆœ€้–‹ๅง‹ๆฏๅ€‹้ญš้ƒฝๆœ‰็‰นๅฎš็š„่ตทๅง‹ไฝ็ฝฎ A: ๆดป้ญš็š„ๅคงๅฐ, B: ้ญšๆธธ็š„ๆ–นๅ‘. ๅฆ‚ๆžœๆ–ผ็›ธ้‡็š„่ฉฑๅคง้ญšๆœƒๅƒๆŽ‰ๅฐ้ญš. ่ฟ”ๅ›žๅ‰ฉไธ‹้ญš็š„ๆ•ธ้‡ ่งฃ้กŒๆ€่ทฏ ๅพž B ้–‹ๅง‹ๆ‰พ, ็•ถๅ€ผ็‚บ1 ๅญ˜ๅ…ฅstack. ไปฃ่กจๅ‘ไธ‹ๆธธ็š„้ญš. ไพ†้€ฒ่กŒๆŠŠๆดป้ญšๅƒๆŽ‰. ๅฆ‚ๆžœๆŠŠๅˆ—่กจ็š„ๆดป้ญš้ƒฝๅƒๆŽ‰. ๅ‰‡็ตๆžœ+1 ๅฆ‚ๆžœๅ€ผ็‚บ0ไธ”stack็‚บ็ฉบ, ไปฃ่กจๆฒ’้‡ๅˆฐไธ‹ๆธธ็š„้ญšๆ‰€ไปฅๆดป้ญš++ ไพ†ๆบ https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/Fish/Fish.go package Fish import \"LeetcodeGolang/Utility/structures\" func Solution(A []int, B []int) int { stack := structures.NewArrayStack() aliveFish := 0 for idx, val := range B { if val == 1 { stack.Push(A[idx]) } else { // ็นผ็บŒๅพ€ไธ‹ๆธธ for !stack.IsEmpty() { if stack.Top().(int) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0007.Stacks-and-Queues/Nesting/":{"url":"Codility/Lesson/0007.Stacks-and-Queues/Nesting/","title":"Nesting","keywords":"","body":"Nesting Determine whether a given string of parentheses (single type) is properly nested. A string S consisting of N characters is called properly nested if: S is empty; S has the form \"(U)\" where U is a properly nested string; S has the form \"VW\" where V and W are properly nested strings. For example, string \"(()(())())\" is properly nested but string \"())\" isn't. Write a function: func Solution(S string) int that, given a string S consisting of N characters, returns 1 if string S is properly nested and 0 otherwise. For example, given S = \"(()(())())\", the function should return 1 and given S = \"())\", the function should return 0, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..1,000,000]; string S consists only of the characters \"(\" and/or \")\". Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆ‹ฌ่™Ÿ้…ๅฐ ่งฃ้กŒๆ€่ทฏ ่ˆ‡Bracket้กžไผผ ไพ†ๆบ https://app.codility.com/programmers/lessons/7-stacks_and_queues/nesting/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/Nesting/Nesting.go package Nesting import \"LeetcodeGolang/Utility/structures\" func Solution(S string) int { if len(S) == 0 { return 1 } if len(S)%2 != 0 { return 0 } stack := structures.NewArrayStack() for _, v := range S { val := string(v) if val == \"(\" { stack.Push(val) } else if val == \")\" { stack.Pop() } } if stack.IsEmpty() { return 1 } else { return 0 } } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0007.Stacks-and-Queues/StoneWall/":{"url":"Codility/Lesson/0007.Stacks-and-Queues/StoneWall/","title":"Stone Wall","keywords":"","body":"StoneWall Cover \"Manhattan skyline\" using the minimum number of rectangles. You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[Nโˆ’1] is the height of the wall's right end. The wall should be built of cuboid (้•ทๆ–น้ซ”) stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall. Write a function: func Solution(H []int) int that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it. For example, given array H containing N = 9 integers: H[0] = 8 H[1] = 8 H[2] = 5 H[3] = 7 H[4] = 9 H[5] = 8 H[6] = 7 H[7] = 4 H[8] = 8 the function should return 7. The figure shows one possible arrangement of seven blocks. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array H is an integer within the range [1..1,000,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๅฆ‚ไฝ•็”จๆœ€ๅฐ‘็š„ๆ•ธ้‡ไพ†่ฒผๅ‡บ็ฌฆๅˆ H ็š„็‰†ๅ‘ข ่ฆๅปบ็ซ‹ไธ€้ข้•ทN็ฑณ็š„ๅผท. ๅŽšๅบฆๅ›บๅฎš, ๆฏๅ€‹ๅœฐๆ–น็š„้ซ˜ๅบฆไธๅŒ. H[I]ไปฃ่กจ็‰†ๅพž I ๅˆฐ I+1 ็ฑณ่™•็š„้ซ˜ๅบฆ. H[0]ๅคง่กจ็‰†ๆœ€ๅทฆๅˆฐ1็ฑณ่™•็š„้ซ˜ๅบฆ H[N-1]ๅคง่กจ็‰†N-1็ฑณ่™•ๅˆฐๆœ€ๅณ็š„้ซ˜ๅบฆ ่งฃ้กŒๆ€่ทฏ ๅฐ‹้ๆ•ดๅ€‹array, ็•ถ็•ถๅ‰้ซ˜ๅบฆๅคงๆ–ผๅ…ˆๅ‰้ซ˜ๅบฆๆ™‚,ๅŠ ๅ…ฅstack่ฃก, ไธฆ่ฆ–็‚บไธ€ๅ€‹็Ÿฉๅฝข. ๅฐ‡็ตๆžœ+1 ่‹ฅ็•ถๅ‰้ซ˜ๅบฆๅฐๆ–ผๅ…ˆๅ‰,ๅฐ‡ๅ…ˆๅ‰้ซ˜ๅบฆpopๅ‡บๅŽป.็›ดๅˆฐstack ็‚บ็ฉบๆˆ–็•ถๅ‰้ซ˜ๅบฆๅคงๆ–ผ็ญ‰ๆ–ผๅ…ˆๅ‰้ซ˜ๅบฆ ไพ†ๆบ https://app.codility.com/programmers/lessons/7-stacks_and_queues/stone_wall/ https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L7_Stacks%20and%20Queues/7.4%20StoneWall.md ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/StoneWall.go package StoneWall import \"LeetcodeGolang/Utility/structures\" func Solution(H []int) int { stack := structures.NewArrayStack() result := 0 for _, v := range H { for !stack.IsEmpty() && stack.Top().(int) > v { stack.Pop() } if stack.IsEmpty() || stack.Top().(int) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0008.Leader/Dominator/":{"url":"Codility/Lesson/0008.Leader/Dominator/","title":"Dominator","keywords":"","body":"Dominator Find an index of an array such that its value occurs at more than half of indices in the array. An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A. For example, consider array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8. Write a function func Solution(A []int) int that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return โˆ’1 if array A does not have a dominator. For example, given array A such that A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 the function may return 0, 2, 4, 6 or 7, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer within the range [โˆ’2,147,483,648..2,147,483,647]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่ฟ”ๅ›žArrayไธญ็š„ๆ”ฏ้…ๆ•ธ. A็š„ๆ”ฏ้…ๆ•ธๆ˜ฏ3๏ผŒๅ› ็‚บๅฎƒๅ‡บ็พๅœจA็š„8ๅ€‹ๅ…ƒ็ด ไธญ็š„5ๅ€‹ๅ…ƒ็ด ไธญ(index็‚บ0ใ€2ใ€4ใ€6ๅ’Œ7). ่€Œ5ๆ˜ฏ8็š„ไธ€ๅŠไปฅไธŠ ๅฏไปฅ่ฟ”ๅ›ž 0,2,4,6,7ไธญ็š„ไปปไธ€ๆ•ธ ่งฃ้กŒๆ€่ทฏ ็”จmap็ด€้Œ„ๆฏ็ญ†ๆ•ธๅ‡บ็พๆฌกๆ•ธ. ๅ–ๆœ€ๅคงๆฌกๆ•ธ็œ‹ๆ˜ฏๅฆๆœ‰่ถ…้Žไธ€ๅŠไปฅไธŠ. ๆ˜ฏ็š„่ฉฑ่ฟ”ๅ›žๆญคๆ•ธไปปไธ€ๅ€‹index, ๅไน‹่ฟ”ๅ›ž-1 ไพ†ๆบ https://app.codility.com/programmers/lessons/8-leader/dominator/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0008.Leader/Dominator/Dominator.go package Dominator import ( \"math\" ) func Solution(A []int) int { mapInt := make(map[int]int, len(A)) for _, v := range A { if _, ok := mapInt[v]; !ok { mapInt[v] = 1 } else { mapInt[v]++ } } maxCount := 0 maxVal := 0 for k, v := range mapInt { if v > maxCount { maxCount = v maxVal = k } } minIndex := -1 for k, v := range A { if v == maxVal { minIndex = k break } } if maxCount > int(math.Floor(float64(len(A))/2.0)) { return minIndex } else { return -1 } } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0008.Leader/EquiLeader/":{"url":"Codility/Lesson/0008.Leader/EquiLeader/","title":"Equi Leader","keywords":"","body":"EquiLeader Find the index S such that the leaders of the sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N - 1] are the same. A non-empty array A consisting of N integers is given. The leader of this array is the value that occurs in more than half of the elements of A. An equi leader is an index S such that 0 โ‰ค S For example, given array A such that: A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 we can find two equi leaders: 0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4. 2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4. The goal is to count the number of equi leaders. Write a function: func Solution(A []int) int that, given a non-empty array A consisting of N integers, returns the number of equi leaders. For example, given: A[0] = 4 A[1] = 3 A[2] = 4 A[3] = 4 A[4] = 4 A[5] = 2 the function should return 2, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [โˆ’1,000,000,000..1,000,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ้ธๅฎšไธ€ๅ€‹ไธ‹ๆจ™, ๅฐ‡ไธ€ๅ€‹ๆ•ธ็ต„ๅˆ†็ˆฒๅทฆๅณๅ…ฉๅ€‹ๅญๆ•ธ็ต„, ไฝฟๅพ—ๅ…ฉๅ€‹ๅญๆ•ธ็ต„้ƒฝๆœ‰็›ธๅŒ็š„leader, ๅ‰‡็จฑๆญคไธ‹ๆจ™็ˆฒEquiLeader, ่ฆๆฑ‚่ฟ”ๅ›ž็ตฆๅฎšๆ•ธ็ต„ไธญEquiLeader็š„ๅ€‹ๆ•ธn. ไบ‹ๅฏฆไธŠ, ่‹ฅไธ€ๅ€‹ๆ•ธๅŒๆ™‚ๆ˜ฏๅทฆๅญๆ•ธ็ต„็š„leader, ๅฎƒๅฟ…็„ถไนŸๆ˜ฏๆ•ดๅ€‹ๆ•ธ็ต„็š„leader. ่งฃ้กŒๆ€่ทฏ ้œ€่ฆๅ…ˆๆ‰พๅ‡บๅบๅˆ—ไธญ็š„leader, ่จ˜้Œ„ๅ…ถๅ‡บ็พ็š„ๆฌกๆ•ธ. ็„ถๅพŒๅ†้ๆญทๆ•ดๅ€‹ๆ•ธ็ต„๏ผŒๆžš่ˆ‰ๅˆ†ๅ‰ฒ้ปž๏ผŒ่จ˜้Œ„ไธ‹ๅทฆๅญๆ•ธ็ต„leaderๅ‡บ็พ็š„ๆฌกๆ•ธs, ็œ‹s่ˆ‡n-sๆ˜ฏๅฆ่ƒฝไฝฟๅพ—leaderๅœจๅทฆๅณๅญๆ•ธ็ต„ไธญไป็ˆฒleader. ไพ†ๆบ https://app.codility.com/programmers/lessons/8-leader/equi_leader/ https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L8_Leader/8.1%20EquiLeader.md ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0008.Leader/EquiLeader/EquiLeader.go package EquiLeader func Solution(A []int) int { leaderDict := make(map[int]int) for i := 0; i times { times = v leader = k } } equiCount := 0 count := 0 // ่ถ…้ ปๆ•ธๅทฒๅ‡บ็พ็š„ๆฌกๆ•ธ for index, v := range A { if v == leader { count++ } if count > (index+1)/2 && (times-count) > (len(A)-(index+1))/2 { equiCount++ } } return equiCount } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/":{"url":"Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/","title":"Max Double Slice Sum","keywords":"","body":"MaxDoubleSliceSum Find the maximal sum of any double slice. A non-empty array A consisting of N integers is given. A triplet (X, Y, Z), such that 0 โ‰ค X The sum of double slice (X, Y, Z) is the total of A[X + 1] + A[X + 2] + ... + A[Y โˆ’ 1] + A[Y + 1] + A[Y + 2] + ... + A[Z โˆ’ 1]. For example, array A such that: A[0] = 3 A[1] = 2 A[2] = 6 A[3] = -1 A[4] = 4 A[5] = 5 A[6] = -1 A[7] = 2 contains the following example double slices: double slice (0, 3, 6), sum is 2 + 6 + 4 + 5 = 17, double slice (0, 3, 7), sum is 2 + 6 + 4 + 5 โˆ’ 1 = 16, double slice (3, 4, 5), sum is 0. The goal is to find the maximal sum of any double slice. Write a function: func Solution(A []int) int that, given a non-empty array A consisting of N integers, returns the maximal sum of any double slice. For example, given: A[0] = 3 A[1] = 2 A[2] = 6 A[3] = -1 A[4] = 4 A[5] = 5 A[6] = -1 A[7] = 2 the function should return 17, because no double slice of array A has a sum of greater than 17. Write an efficient algorithm for the following assumptions: N is an integer within the range [3..100,000]; each element of array A is an integer within the range [โˆ’10,000..10,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ A[X+1]ๅˆฐA[Y-1] + A[Y+1]ๅˆฐA[Z-1] ๆœ€ๅคง็š„ๅ’Œ ่งฃ้กŒๆ€่ทฏ ๆญฃๅ‘ๅฐ‹้Žarray, ็ฒๅพ—ๅˆฐ้”ๆฏๅ€‹indexๅฏไปฅๅพ—ๅˆฐ็š„ๆœ€ๅคงๅ€ผๅบๅˆ—, ็„ถๅŽๅๅ‘ๅฐ‹้Žarray็ฒๅพ—ๅˆฐ้”ๆฏๅ€‹indexๅฏไปฅๅพ—ๅˆฐ็š„ๆœ€ๅคงๅ€ผๅบๅˆ—๏ผŒ ๅๅ‘็š„็š„ๆœ€ๅคงๅ€ผๅบๅˆ—้œ€่ฆๅ€’่ฝ‰.็„ถๅพŒ้–“้š”ไธ€ๅ€‹ไฝ็ฝฎ๏ผŒ ๆœ€ๅพŒๅฐ‹้array่ตทๅ…ฉ่€…็›ธๅŠ ๆœ€ๅคงๅ€ผ ไพ†ๆบ https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_double_slice_sum/ https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L9_Maximum%20Slice%20Problem/9.3%20%20MaxDoubleSliceSum.md ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/MaxDoubleSliceSum.go package MaxDoubleSliceSum import ( \"math\" ) func Solution(A []int) int { if len(A) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/":{"url":"Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/","title":"Max Profit","keywords":"","body":"MaxProfit Given a log of stock prices compute the maximum possible earning. An array A consisting of N integers is given. It contains daily prices of a stock share for a period of N consecutive days. If a single share was bought on day P and sold on day Q, where 0 โ‰ค P โ‰ค Q For example, consider the following array A consisting of six elements such that: A[0] = 23171 A[1] = 21011 A[2] = 21123 A[3] = 21366 A[4] = 21013 A[5] = 21367 If a share was bought on day 0 and sold on day 2, a loss of 2048 would occur because A[2] โˆ’ A[0] = 21123 โˆ’ 23171 = โˆ’2048. If a share was bought on day 4 and sold on day 5, a profit of 354 would occur because A[5] โˆ’ A[4] = 21367 โˆ’ 21013 = 354. Maximum possible profit was 356. It would occur if a share was bought on day 1 and sold on day 5. Write a function, func Solution(A []int) int that, given an array A consisting of N integers containing daily prices of a stock share for a period of N consecutive days, returns the maximum possible profit from one transaction during this period. The function should return 0 if it was impossible to gain any profit. For example, given array A consisting of six elements such that: A[0] = 23171 A[1] = 21011 A[2] = 21123 A[3] = 21366 A[4] = 21013 A[5] = 21367 the function should return 356, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..400,000]; each element of array A is an integer within the range [0..200,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่จˆ็ฎ—่‚ก็ฅจๅฏ่ƒฝ็ฒๅพ—็š„ๆœ€ๅคงๅˆฉๆฝค ่งฃ้กŒๆ€่ทฏ ๅฐ‹้ๆ•ดๅ€‹array, ๆ‰พๅ‡บๆœ€ๅฐ็š„่ฒทๅ…ฅ้‡‘้ก, ๅŒๆ™‚่จˆ็ฎ—็•ถๅ‰็š„่ณฃๅ‡บ้‡‘้ก-ๆœ€ๅฐ่ฒทๅ…ฅ้‡‘้ก, ๅพ—ๅ‡บๆœ€ๅคงๅˆฉๆฝค ไพ†ๆบ https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_profit/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/MaxProfit.go package MaxProfit import ( \"math\" ) func Solution(A []int) int { minBuyPrice := math.MaxFloat64 maxProfit := 0.0 for _, v := range A { minBuyPrice = math.Min(minBuyPrice, float64(v)) maxProfit = math.Max(maxProfit, float64(v)-minBuyPrice) } return int(maxProfit) } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/":{"url":"Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/","title":"Max Slice Sum","keywords":"","body":"MaxSliceSum Find a maximum sum of a compact subsequence of array elements. A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 โ‰ค P โ‰ค Q Write a function: func Solution(A []int) int that, given an array A consisting of N integers, returns the maximum sum of any slice of A. For example, given array A such that: A[0] = 3 A[1] = 2 A[2] = -6 A[3] = 4 A[4] = 0 the function should return 5 because: (3, 4) is a slice of A that has sum 4, (2, 2) is a slice of A that has sum โˆ’6, (0, 1) is a slice of A that has sum 5, no other slice of A has sum greater than (0, 1). Write an efficient algorithm for the following assumptions: N is an integer within the range [1..1,000,000]; each element of array A is an integer within the range [โˆ’1,000,000..1,000,000]; the result will be an integer within the range [โˆ’2,147,483,648..2,147,483,647]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆ‰พๅ‡บ้€ฃ็บŒๅญๅบๅˆ—ๆœ€ๅคง็š„ๅ’Œ ่งฃ้กŒๆ€่ทฏ ้•ทๅบฆๅฆ‚ๆžœ็‚บ1, ๅ›žๅ‚ณ็ฌฌไธ€็ญ† ็•ถไธ‹็š„ๅ€ผ่ทŸ็•ถไธ‹็š„ๅ€ผๅŠ ไธŠๅ…ˆๅ‰็š„ๅ’Œ, ๅ–ๆœ€ๅคงๅ€ผ. ๅ†ๅฐ‡ๅ‰›ๅ‰›็ฎ—ๅ‡บ็š„ๆœ€ๅคงๅ€ผ่ทŸ็ด€้Œ„ไธญ็š„ๆœ€ๅคงๅ€ผๆฏ”่ผƒ,ๅ–ๆœ€ๅคงๅ€ผ ไพ†ๆบ https://app.codility.com/programmers/lessons/9-maximum_slice_problem/max_slice_sum/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/MaxSliceSum.go package MaxSliceSum import ( \"math\" ) func Solution(A []int) int { if len(A) == 1 { return A[0] } result := math.MinInt64 sum := math.MinInt64 for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/":{"url":"Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/","title":"Count Factors","keywords":"","body":"CountFactors Count factors of given number n. A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M. For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4). Write a function: func Solution(N int) int that, given a positive integer N, returns the number of its factors. For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..2,147,483,647]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๆ‰พๅ‡บ่ฉฒๆ•ธ็š„ๅ› ๅญๅ€‹ๆ•ธ ่งฃ้กŒๆ€่ทฏ ๅฐ‹้่ฉฒๆ•ธๅญ—ๅนณๆ–นๆ น็š„ๆ•ดๆ•ธ, ๆฏๆฌกๅฏไปฅ็ฒๅพ—2ๅ€‹ๅ› ๅญ ไพ†ๆบ https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/count_factors/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/CountFactors.go package CountFactors import ( \"math\" ) func Solution(N int) int { result := 0 for i := 1; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/":{"url":"Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/","title":"Flags","keywords":"","body":"Flags Find the maximum number of flags that can be set on mountain peaks. A non-empty array A consisting of N integers is given. A peak is an array element which is larger than its neighbours. More precisely, it is an index P such that 0 A[P + 1]. For example, the following array A: A[0] = 1 A[1] = 5 //peaks A[2] = 3 A[3] = 4 //peaks A[4] = 3 A[5] = 4 //peaks A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 //peaks A[11] = 2 has exactly four peaks: elements 1, 3, 5 and 10. You are going on a trip to a range of mountains whose relative heights are represented by array A, as shown in a figure below. You have to choose how many flags you should take with you. The goal is to set the maximum number of flags on the peaks, according to certain rules. Flags can only be set on peaks. What's more, if you take K flags, then the distance between any two flags should be greater than or equal to K. The distance between indices P and Q is the absolute value |P โˆ’ Q|. For example, given the mountain range represented by array A, above, with N = 12, if you take: two flags, you can set them on peaks 1 and 5; three flags, you can set them on peaks 1, 5 and 10; four flags, you can set only three flags, on peaks 1, 5 and 10. You can therefore set a maximum of three flags in this case. Write a function: func Solution(A []int) int that, given a non-empty array A of N integers, returns the maximum number of flags that can be set on the peaks of the array. For example, the following array A: A[0] = 1 A[1] = 5 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 the function should return 3, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..400,000]; each element of array A is an integer within the range [0..1,000,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่จˆ็ฎ—ๅฏไปฅๅœจๅฑฑๅณฐไธŠ่จญ็ฝฎ็š„ๆœ€ๅคงๆ——ๆจ™ๆ•ธ้‡ ๆ——ๆจ™ๅช่ƒฝๅœจๅฑฑๅณฐไธŠ่จญ็ฝฎ, ๅฆ‚ๆžœๅธถไบ†Kๅ€‹ๆ——ๆจ™, ๅ‰‡ไปปๆ„ๅ…ฉๅ€‹ๆ——ๆจ™็š„็ดขๅผ•่ท้›ขไธ่ƒฝๅฐๆ–ผK ่งฃ้กŒๆ€่ทฏ ๅ…ˆๆ‰พๅ‡บpeak็š„็ดขๅผ•ไฝ็ฝฎไธฆๅญ˜ๅ…ฅarrayไธญ. ๆ นๆ“špeak array็š„็ฌฌไธ€ๅ€‹ๆœ€ๅพŒไธ€ๅ€‹ๅฏไปฅๅˆคๆ–ท็†่ซ–ไธŠๆœ€ๅคš็š„ๆ——ๆจ™ๆ•ธ็‚บK: K*(K-1) ไพ†ๆบ https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/ https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L10_Prime%20and%20composite%20numbers/10.4%20Flags.md ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/Flags.go package Flags import ( \"math\" ) func Solution(A []int) int { var peaksFlag []int for i := 1; i A[i-1] && A[i] > A[i+1] { peaksFlag = append(peaksFlag, i) } } if len(peaksFlag) == 0 { return 0 } if len(peaksFlag) == 1 { return 1 } maxFlag := int(math.Pow(float64(peaksFlag[len(peaksFlag)-1]-peaksFlag[0]), 0.5) + 1) for i := maxFlag; i > 1; i-- { addressFlag := []int{peaksFlag[0]} for _, val := range peaksFlag[1:] { if val-addressFlag[len(addressFlag)-1] >= i { addressFlag = append(addressFlag, val) if len(addressFlag) >= i { return i } } } } return 1 } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/":{"url":"Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/","title":"Min Perimeter Rectangle","keywords":"","body":"MinPerimeterRectangle Find the minimal perimeter of any rectangle whose area equals N. An integer N is given, representing the area of some rectangle. The area of a rectangle whose sides are of length A and B is A B, and the perimeter is 2 (A + B). The goal is to find the minimal perimeter of any rectangle whose area equals N. The sides of this rectangle should be only integers. For example, given integer N = 30, rectangles of area 30 are: (1, 30), with a perimeter of 62, (2, 15), with a perimeter of 34, (3, 10), with a perimeter of 26, (5, 6), with a perimeter of 22. Write a function: func Solution(N int) int that, given an integer N, returns the minimal perimeter of any rectangle whose area is exactly equal to N. For example, given an integer N = 30, the function should return 22, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..1,000,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ็ตฆๆ•ดๆ•ธ็š„้ข็ฉN, ๆ‰พๅ‡บ้ข็ฉ็‚บN็š„ๆœ€ๅฐๅ‘จ้•ท ่งฃ้กŒๆ€่ทฏ ๅพžไธๅคงๆ–ผN็š„ๅนณๆ–นๆ น็š„ๆ•ธ้–‹ๅง‹้ๆญท,ๅช่ฆๆ‰พๅˆฐN็š„ๅ› ๅญ ๅ› ็‚บ่ถŠๅพ€ๅพŒๆ‰€ๅพ—็š„ๅ‘จ้•ท่ถŠๅคง.้‚Š้•ทๆŽฅ่ฟ‘ๅนณๆ–นๆ น็š„็Ÿฉๅฝข็š„ๅ‘จ้•ทๆ˜ฏๆœ€ๅฐ็š„ ไพ†ๆบ https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/min_perimeter_rectangle/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/MinPerimeterRectangle.go package minperimeterrectangle import ( \"math\" ) // O(sqrt(N)) func Solution(N int) int { if N ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/":{"url":"Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/","title":"Peaks","keywords":"","body":"Peaks Divide an array into the maximum number of same-sized blocks, each of which should contain an index P such that A[P - 1] A[P + 1]. A non-empty array A consisting of N integers is given. A peak is an array element which is larger than its neighbors. More precisely, it is an index P such that 0 A[P + 1]. For example, the following array A: A[0] = 1 A[1] = 2 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 has exactly three peaks: 3, 5, 10. We want to divide this array into blocks containing the same number of elements. More precisely, we want to choose a number K that will yield the following blocks: A[0], A[1], ..., A[K โˆ’ 1], A[K], A[K + 1], ..., A[2K โˆ’ 1], ... A[N โˆ’ K], A[N โˆ’ K + 1], ..., A[N โˆ’ 1]. What's more, every block should contain at least one peak. Notice that extreme elements of the blocks (for example A[K โˆ’ 1] or A[K]) can also be peaks, but only if they have both neighbors (including one in an adjacent blocks). The goal is to find the maximum number of blocks into which the array A can be divided. Array A can be divided into blocks as follows: one block (1, 2, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2). This block contains three peaks. two blocks (1, 2, 3, 4, 3, 4) and (1, 2, 3, 4, 6, 2). Every block has a peak. three blocks (1, 2, 3, 4), (3, 4, 1, 2), (3, 4, 6, 2). Every block has a peak. Notice in particular that the first block (1, 2, 3, 4) has a peak at A[3], because A[2] A[4], even though A[4] is in the adjacent block. However, array A cannot be divided into four blocks, (1, 2, 3), (4, 3, 4), (1, 2, 3) and (4, 6, 2), because the (1, 2, 3) blocks do not contain a peak. Notice in particular that the (4, 3, 4) block contains two peaks: A[3] and A[5]. The maximum number of blocks that array A can be divided into is three. Write a function: func Solution(A []int) int that, given a non-empty array A consisting of N integers, returns the maximum number of blocks into which A can be divided. If A cannot be divided into some number of blocks, the function should return 0. For example, given: A[0] = 1 A[1] = 2 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 the function should return 3, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [0..1,000,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๅฐ‡ array ๅˆ†ๆˆๅŒๆจฃ้•ทๅบฆ็š„ๅ€ๅกŠ, ่ฒทๅ€‹ๅ€ๅกŠ่‡ณๅฐ‘ๅŒ…ๅซไธ€ๅ€‹peak. ่งฃ้กŒๆ€่ทฏ ๅ…ˆๆ‰พๅ‡บๆ‰€ๆœ‰peak็š„index ๅฏซๅ…ฅpeaks array. \bๅพžpeaks็š„้•ทๅบฆ้–‹ๅง‹ๅพ€ไธ‹ๆ‰พ, ๅฐ‡ A ๆ‹†ๆˆๅ€ๅกŠ, ๆฏๅ€‹ๅ€ๅกŠๆชขๆŸฅๆ˜ฏๅฆๆœ‰ๆœ‰ๆ‰พๅˆฐpeak ไพ†ๆบ https://app.codility.com/programmers/lessons/10-prime_and_composite_numbers/peaks/ https://www.martinkysel.com/codility-peaks-solution/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/Peaks.go package peaks /* expected worst-case time complexity is O(N*log(log(N))); expected worst-case space complexity is O(N) */ func Solution(A []int) int { // ๅ…ˆๆ‰พๅ‡บpeaks peaks := []int{} for i := 1; i A[i+1] { peaks = append(peaks, i) } } if len(peaks) 0; size-- { if len(A)%size == 0 { // ๆฏๅ€‹ๅ€ๅกŠ็š„size blockSize := len(A) / size found := make(map[int]bool, size) foundCnt := 0 for _, peak := range peaks { // ๆชขๆŸฅๆฏๅ€‹ๅ€ๅกŠๆ˜ฏๅฆๆœ‰ๆ‰พๅˆฐ peak blockNr := peak / blockSize if ok := found[blockNr]; !ok { found[blockNr] = true foundCnt++ } } if foundCnt == size { return size } } } return 0 } /* def solution(A): peaks = [] for idx in range(1, len(A)-1): if A[idx-1] A[idx+1]: peaks.append(idx) if len(peaks) == 0: return 0 for size in range(len(peaks), 0, -1): if len(A) % size == 0: block_size = len(A) // size found = [False] * size found_cnt = 0 for peak in peaks: block_nr = peak//block_size if found[block_nr] == False: found[block_nr] = True found_cnt += 1 if found_cnt == size: return size return 0 */ ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/":{"url":"Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/","title":"Count Non Divisible","keywords":"","body":"CountNonDivisible Calculate the number of elements of an array that are not divisors(ๅ› ๆ•ธ) of each element. You are given an array A consisting of N integers. For each number A[i] such that 0 โ‰ค i For example, consider integer N = 5 and array A such that: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 For the following elements: A[0] = 3, the non-divisors are: 2, 6, A[1] = 1, the non-divisors are: 3, 2, 3, 6, A[2] = 2, the non-divisors are: 3, 3, 6, A[3] = 3, the non-divisors are: 2, 6, A[4] = 6, there aren't any non-divisors. Write a function: func Solution(A []int) []int that, given an array A consisting of N integers, returns a sequence of integers representing the amount of non-divisors. Result array should be returned as an array of integers. For example, given: A[0] = 3 A[1] = 1 A[2] = 2 A[3] = 3 A[4] = 6 the function should return [2, 4, 3, 2, 0], as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..50,000]; each element of array A is an integer within the range [1..2 * N]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ็ฎ—ๅ‡บarrayไธญๆ‰€ๆœ‰ๅ…ƒ็ด ็š„้žๅ› ๅญๆ•ธ็š„ๅ€‹ๆ•ธ ่งฃ้กŒๆ€่ทฏ ๅ…ˆ็ฎ—ๆ•ธๆฏๅ€‹ๆ•ธๅญ—ๅ‡บ็พ็š„ๆฌกๆ•ธๅญ˜ๅ…ฅmap ้ๆญทA, ๅฐๆ–ผๆฏๅ€‹ๅ…ƒ็ด ๅพž1ๅˆฐsqrt(i)ไธญๆ‰พๅ‡บๅ› ๅญ,ๅฆ‚ๆžœๆ˜ฏๅ› ๅญ,ๅฐฑๅŽปๅญ—ๅ…ธๆ‰พๅ‡บๅ‡บ็พๆฌกๆ•ธ ๆœ€ๅพŒ็”จ็ธฝ้•ทๅบฆๆธ›ๅŽปๅ› ๅญๆ•ธๅฐฑๅฏๅพ—ๅ‡บ้žๅ› ๅญๆ•ธ, ไธฆๅฐ‡็ตๆžœๅญ˜ๅ…ฅmap, ็ฉบ้–“ๆ›ๅ–ๆ™‚้–“ factor ไพ†ๆบ https://app.codility.com/programmers/lessons/11-sieve_of_eratosthenes/count_non_divisible/ https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L11_Sieve%20of%20Eratosthenes/11.1%20CountNonDivisible.md ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/CountNonDivisible.go package countnondivisible import ( \"math\" ) /* Task Score 100% Correctness 100% Performance 100% */ func Solution(A []int) []int { // write your code in Go 1.4 result := []int{} if len(A) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/":{"url":"Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/","title":"Count Semiprimes","keywords":"","body":"CountSemiprimes Count the semiprime(ๅŠ่ณชๆ•ธ:ๅ…ฉๅ€‹่ณชๆ•ธ็š„ไน˜็ฉๆ‰€ๅพ—็š„่‡ช็„ถๆ•ธๆˆ‘ๅ€‘็จฑไน‹็‚บๅŠ่ณชๆ•ธ) numbers in the given range [a..b] A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13. A semiprime is a natural number that is the product of two (not necessarily distinct) prime numbers. The first few semiprimes are 4, 6, 9, 10, 14, 15, 21, 22, 25, 26. You are given two non-empty arrays P and Q, each consisting of M integers. These arrays represent queries about the number of semiprimes within specified ranges. Query K requires you to find the number of semiprimes within the range (P[K], Q[K]), where 1 โ‰ค P[K] โ‰ค Q[K] โ‰ค N. For example, consider an integer N = 26 and arrays P, Q such that: P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20 The number of semiprimes within each of these ranges is as follows: (1, 26) is 10, (4, 10) is 4, (16, 20) is 0. Write a function: func Solution(N int, P []int, Q []int) []int that, given an integer N and two non-empty arrays P and Q consisting of M integers, returns an array consisting of M elements specifying the consecutive answers to all the queries. For example, given an integer N = 26 and arrays P, Q such that: P[0] = 1 Q[0] = 26 P[1] = 4 Q[1] = 10 P[2] = 16 Q[2] = 20 the function should return the values [10, 4, 0], as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..50,000]; M is an integer within the range [1..30,000]; each element of arrays P, Q is an integer within the range [1..N]; P[i] โ‰ค Q[i]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ่จˆ็ฎ—[a,b]ๅ€้–“ๅพ—ๅŠ่ณชๆ•ธ็š„ๅ€‹ๆ•ธ ่งฃ้กŒๆ€่ทฏ ๅ…ˆๆŠŠๅŠ่ณชๆ•ธๅˆ—่กจๆ‰พๅ‡บไพ†. (ๅŠ่ณชๆ•ธ:ๅ…ฉๅ€‹่ณชๆ•ธ็š„ไน˜็ฉๆ‰€ๅพ—็š„่‡ช็„ถๆ•ธๆˆ‘ๅ€‘็จฑไน‹็‚บๅŠ่ณชๆ•ธใ„้–‹ๅง‹็š„ๅนพๅ€‹ๅŠ่ณชๆ•ธๆ˜ฏ4, 6, 9, 10, 14, 15, 21, 22, 25, 26, ... ๏ผˆOEISไธญ็š„ๆ•ธๅˆ—A001358๏ผ‰ๅฎƒๅ€‘ๅŒ…ๅซ1ๅŠ่‡ชๅทฑๅœจๅ…งๅˆๅ…ฑๆœ‰3ๆˆ–4ๅ€‹ๅ› ๆ•ธ) ่จˆ็ฎ—็•ถๅ‰arrayๅ’Œๅ‰้ขไธ€ๅ…ฑๆœ‰ๅนพๅ€‹ๅŠ่ณชๆ•ธ ้ๆญทP arry ็ฎ—ๅ‡บ Q่ทŸP ไน‹ๅ‰็š„ๅŠ่ณชๆ•ธ็ธฝๅ’Œๅทฎ, ไธฆๅฏซๅ…ฅ็ตๆžœ ไพ†ๆบ https://app.codility.com/programmers/lessons/11-sieve_of_eratosthenes/count_semiprimes/ https://github.com/Luidy/codility-golang/blob/master/Lesson11/02_countSemiprimes.go https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L11_Sieve%20of%20Eratosthenes/11.2%20CountSemiprimes.md ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/CountSemiprimes.go package countsemiprimes func Solution(N int, P []int, Q []int) []int { semiPrime := []int{} // ๅŠ่ณชๆ•ธ:ๅ…ฉๅ€‹่ณชๆ•ธ็š„ไน˜็ฉๆ‰€ๅพ—็š„่‡ช็„ถๆ•ธๆˆ‘ๅ€‘็จฑไน‹็‚บๅŠ่ณชๆ•ธ. // 4, 6, 9, 10, 14, 15, 21,22,25,26,33,34,35,38,39,46,49,51,55,57,58,62,65,69,74,77,82,85,86,87,91,93,94,95,106, ... // ๅฎƒๅ€‘ๅŒ…ๅซ1ๅŠ่‡ชๅทฑๅœจๅ…งๅˆๅ…ฑๆœ‰3ๆˆ–4ๅ€‹ๅ› ๆ•ธ for i := 1; i 4 { sign = 1 semiPrime = append(semiPrime, 0) break } } if sign != 1 { if factorCount >= 3 { semiPrime = append(semiPrime, i) } else { semiPrime = append(semiPrime, 0) } } } // idx 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 // semiPrime 0 0 0 4 0 6 0 0 9 10 0 0 0 14 15 0 0 0 0 0 21 22 0 0 25 26 // fmt.Println(\"semiPrime\", semiPrime) // ็•ถๅ‰arrayๅ’Œๅ‰้ขไธ€ๅ…ฑๆœ‰ๅนพๅ€‹ๅŠ่ณชๆ•ธ indexMap := make(map[int]int) // ๅฆ‚ๆžœๆ˜ฏๅŠ่ณชๆ•ธๆทปๅŠ ๅˆฐ map semiMap := make(map[int]struct{}) count := 0 for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/":{"url":"Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/","title":"Chocolates By Numbers","keywords":"","body":"ChocolatesByNumbers There are N chocolates in a circle. Count the number of chocolates you will eat. Two positive integers N and M are given. Integer N represents the number of chocolates arranged in a circle, numbered from 0 to N โˆ’ 1. You start to eat the chocolates. After eating a chocolate you leave only a wrapper. You begin with eating chocolate number 0. Then you omit(ๅฟฝ็•ฅ) the next M โˆ’ 1 chocolates or wrappers on the circle, and eat the following one. More precisely(ๆฐๆฐ), if you ate chocolate number X, then you will next eat the chocolate with number (X + M) modulo N (remainder of division). You stop eating when you encounter an empty wrapper. For example, given integers N = 10 and M = 4. You will eat the following chocolates: 0, 4, 8, 2, 6. The goal is to count the number of chocolates that you will eat, following the above rules. Write a function: func Solution(N int, M int) int that, given two positive integers N and M, returns the number of chocolates that you will eat. For example, given integers N = 10 and M = 4. the function should return 5, as explained above. Write an efficient algorithm for the following assumptions: N and M are integers within the range [1..1,000,000,000]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ NๅกŠๅทงๅ…‹ๅŠ›,ๅฆ‚ๆžœๅƒ็š„ๆ˜ฏX่™Ÿ ไธ‹ไธ€ๅ€‹ๆ˜ฏๅƒ (X + M) modulo N ่™Ÿ ็ธฝๅ…ฑๅฏไปฅๅƒๅนพ้ก†. ่งฃ้กŒๆ€่ทฏ ๆ–นๆณ•ใ„ง: ๅพž0่™Ÿ้–‹ๅง‹ๅƒ, ไธ‹ไธ€ๅ€‹่™Ÿ็ขผ+M-1่™Ÿ. ่ฟดๅœˆๅŽป่ท‘ ๆ–นๆณ•ไบŒ: ๅฏไปฅๅƒๅˆฐ็š„ๅทงๅ…‹ๅŠ›็š„ๆ•ธ้‡ๅฐฑๆ˜ฏ็ธฝ็š„ๅทงๅ…‹ๅŠ›้ก†ๆ•ธ N ้™คไปฅ N ๅ’Œ M ็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธ. ่จˆ็ฎ— Nๅ’ŒM็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธP, N้™คไปฅPๅพ—ๅˆฐๅ•†ๅณ็‚บ็ญ”ๆกˆ ไพ†ๆบ https://app.codility.com/programmers/lessons/12-euclidean_algorithm/chocolates_by_numbers/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ChocolatesByNumbers.go package chocolatesbynumbers func gcd(N int, M int) int { if N%M == 0 { return M } else { return gcd(M, N%M) } } /* ๅฏไปฅๅƒๅˆฐ็š„ๅทงๅ…‹ๅŠ›็š„ๆ•ธ้‡ๅฐฑๆ˜ฏ็ธฝ็š„ๅทงๅ…‹ๅŠ›้ก†ๆ•ธ N ้™คไปฅ N ๅ’Œ M ็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธ ่จˆ็ฎ— Nๅ’ŒM็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธP, N้™คไปฅPๅพ—ๅˆฐๅ•†ๅณ็‚บ็ญ”ๆกˆ O(log(N + M)) */ func Solution(N int, M int) int { return N / gcd(N, M) } /* Task Score 75% Correctness 100% Performance 50% input (947853, 4453) the solution exceeded the time limit. ๅพž0่™Ÿ้–‹ๅง‹ๅƒ, ไธ‹ไธ€ๅ€‹่™Ÿ็ขผ+M-1่™Ÿ */ func SolutionBurst(N int, M int) int { eaten := make(map[int]struct{}) eatCount := 0 if N == 1 || M == 1 { return N } for { sumNum := eatCount * M startNum := sumNum % N if _, ok := eaten[startNum]; !ok { eaten[startNum] = struct{}{} eatCount++ } else { // ๆ‰พๅˆฐๅทฒๅƒ้Ž็š„ๅทงๅ…‹ๅŠ› break } } return eatCount } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/":{"url":"Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/","title":"Common Prime Divisors","keywords":"","body":"CommonPrimeDivisors Check whether two numbers have the same prime divisors. A prime is a positive integer X that has exactly two distinct divisors: 1 and X. The first few prime integers are 2, 3, 5, 7, 11 and 13. A prime D is called a prime divisor(่ณชๅ› ๆ•ธ) of a positive integer P if there exists a positive integer K such that D * K = P. For example, 2 and 5 are prime divisors of 20. You are given two positive integers N and M. The goal is to check whether the sets of prime divisors of integers N and M are exactly the same. For example, given: N = 15 and M = 75, the prime divisors are the same: {3, 5}; N = 10 and M = 30, the prime divisors aren't the same: {2, 5} is not equal to {2, 3, 5}; N = 9 and M = 5, the prime divisors aren't the same: {3} is not equal to {5}. Write a function: func Solution(A []int, B []int) int that, given two non-empty arrays A and B of Z integers, returns the number of positions K for which the prime divisors of A[K] and B[K] are exactly the same. For example, given: A[0] = 15 B[0] = 75 A[1] = 10 B[1] = 30 A[2] = 3 B[2] = 5 the function should return 1, because only one pair (15, 75) has the same set of prime divisors. Write an efficient algorithm for the following assumptions: Z is an integer within the range [1..6,000]; each element of arrays A, B is an integer within the range [1..2,147,483,647]. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ๅˆคๆ–ทๅ…ฉๅ€‹ๆ•ธๆ˜ฏๅฆๆœ‰็›ธๅŒ็š„่ณชๅ› ๆ•ธ ่งฃ้กŒๆ€่ทฏ ๅ…ˆๅˆคๆ–ทๅ…ฉๆ•ธ็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธ, ๅ†ๅˆคๆ–ทๅ…ฉๅ€‹ๆ•ธๆ˜ฏๅซๆœ‰ๆœ€ๅคงๅ…ฌๅ› ๆ•ธๆฒ’ๆœ‰็š„ๅ› ๅญ 15 , 75 ็š„ๆœ€ๅคงๅ…ฌๅ› ๆ•ธ็‚บ 35 15= 35 75= 355 ไพ†ๆบ https://app.codility.com/programmers/lessons/12-euclidean_algorithm/common_prime_divisors/ https://github.com/Anfany/Codility-Lessons-By-Python3/blob/master/L12_Euclidean%20algorithm/12.2%20CommonPrimeDivisors.md https://github.com/Luidy/codility-golang/blob/master/Lesson12/02_commonPrimeDivisors.go ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/CommonPrimeDivisors.go package commonprimedivisors /* func gcd(a, b int) int { for b != 0 { t := b b = a % b a = t } return a } */ func gcd(N int, M int) int { if N%M == 0 { return M } else { return gcd(M, N%M) } } func Solution(A []int, B []int) int { result := 0 for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/":{"url":"Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/","title":"Fib Frog","keywords":"","body":"FibFrog The Fibonacci sequence is defined using the following recursive formula: F(0) = 0 F(1) = 1 F(M) = F(M - 1) + F(M - 2) if M >= 2 A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position โˆ’1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N. The leaves on the river are represented in an array A consisting of N integers. Consecutive(้€ฃ็บŒ็š„) elements of array A represent consecutive positions from 0 to N โˆ’ 1 on the river. Array A contains only 0s and/or 1s: 0 represents a position without a leaf; 1 represents a position containing a leaf. The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position โˆ’1 to position N). The frog can jump between positions โˆ’1 and N (the banks of the river) and every position containing a leaf. For example, consider array A such that: A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0 The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5. Write a function: func Solution(A []int) int that, given an array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return โˆ’1. For example, given: A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0 the function should return 3, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [0..100,000]; each element of array A is an integer that can have one of the following values: 0, 1. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ้กŒ็›ฎๅคงๆ„ ไธ€ๅชๅฐ้’่›™ๆƒณๅˆฐๅฐๅฒธใ€‚ๅฎƒ้–‹ๅง‹ไฝๆ–ผๆฒณ็š„ๅฆไธ€้‚Š ไฝ็ฝฎ-1, ๆƒณ่ฆๅˆฐๅฐ้ข็š„ๆฒณๅฒธ ไฝ็ฝฎN . ้’่›™ๅฏไปฅ่ทณไปปๆ„่ท้›ข F(K). ๅ…ถไธญF(K)ๆ˜ฏ็ฌฌKๅ€‹ๆ–ๆณข้‚ฃๅฅ‘ๆ•ธ. ไธ”ๆฒณไธŠๆœ‰่จฑๅคšๆจน่‘‰ A[0] = 0 ไปฃ่กจไฝ็ฝฎ 0 ๆฒ’ๆœ‰ๆจน่‘‰, 1 ไปฃ่กจๆœ‰ๆจน่‘‰ ้’่›™ๅฏไปฅๅœจๆจน่‘‰ไน‹้–“่ทณ, ไฝ†ๅช่ƒฝๆœๆฒณๅฒธ N ็š„ๆ–นๅ‘่ทณ ๆ‰พๅ‡บๆœ€ๅฐ่ทณ็š„ๆฌกๆ•ธ ่งฃ้กŒๆ€่ทฏ ๅปฃๅบฆๅ„ชๅ…ˆๆœๅฐ‹ (Breadth-First Search, BFS) ๅ•้กŒ. ๅฐๆ–ผๆฒณไธŠๆœ‰ๆจน่‘‰็š„ไฝ็ฝฎindex, ๅ‰‡้ๆญทๆฏ”indexๅฐ็š„ๆ–ๆณข้‚ฃๅฅ‘ๆ•ธf, ๅช่ฆ index - f ้€™ๅ€‹ไฝ็ฝฎๅฏไปฅ้”ๅˆฐ, ้€™index็š„ไฝ็ฝฎๅฐฑๅฏไปฅ็ถ“้Žไธ€ๆฌก่ทณ่บ้•ทๅบฆ็‚บf ไพ†ๆบ https://app.codility.com/programmers/lessons/13-fibonacci_numbers/fib_frog/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/FibFrog.go package fibfrog /** * @description: ็”ข็”Ÿไธๅคงๆ–ผn็š„ๆ–ๆณข้‚ฃๅฅ‘ๆ•ธ็š„ๅˆ—่กจ * @param {int} N * @return {*} */ func Fib(N int) (fibArr []int) { fibArr = append(fibArr, 0) fibArr = append(fibArr, 1) fibArr = append(fibArr, 1) i := 2 for fibArr[i] 0 { continue } // get the optimal jump count to reach this leaf if A[i] == 1 { // ๆœ‰ๆจน่‘‰ // ้ๆญทๆ–ๆณข้‚ฃๅฅ‘ๆ•ธๅˆ—, ๅฐ‹ๆ‰พๆœ€ๅฐ‘็š„่ทณ่บๆฌกๆ•ธ minJump := i + 1 canJump := false for _, f := range fibArr { previousIdx := i - f if previousIdx reachable[previousIdx] { // ๆญค previousIdx ไฝ็ฝฎๅฏไปฅๅˆฐ้” // fmt.Printf(\"%d :previousIdx = %d reachable = %v \\n\", i, previousIdx, reachable) minJump = reachable[previousIdx] canJump = true } } if canJump { reachable[i] = minJump + 1 } } // fmt.Printf(\"i=%d , reachable = %v \\n\", i, reachable) } if reachable[len(reachable)-1] == 0 { return -1 } return reachable[len(reachable)-1] } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/":{"url":"Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/","title":"Abs Distinct","keywords":"","body":"AbsDistinct A non-empty array A consisting of N numbers is given. The array is sorted in non-decreasing order. The absolute distinct count of this array is the number of distinct absolute values among the elements of the array. For example, consider array A such that: A[0] = -5 A[1] = -3 A[2] = -1 A[3] = 0 A[4] = 3 A[5] = 6 The absolute distinct count of this array is 5, because there are 5 distinct absolute values among the elements of this array, namely 0, 1, 3, 5 and 6. Write a function: func Solution(A []int) int that, given a non-empty array A consisting of N numbers, returns absolute distinct count of array A. For example, given array A such that: A[0] = -5 A[1] = -3 A[2] = -1 A[3] = 0 A[4] = 3 A[5] = 6 the function should return 5, as explained above. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [โˆ’2,147,483,648..2,147,483,647]; array A is sorted in non-decreasing order. Copyright 2009โ€“2021 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. \"ๆœ‰ๅบๆ•ธ็ต„ไธญ็ต•ๅฐๅ€ผไธๅŒ็š„ๆ•ธ็š„ๅ€‹ๆ•ธ\"ๆŒ‡็š„ๆ˜ฏ๏ผŒไธ€ๅ€‹ๅทฒ็ถ“ๆŽ’ๅฅฝๅบ็š„ๆ•ดๆ•ธๆ•ธ็ต„ไธญ็ต•ๅฐๅ€ผไธ็›ธๅŒ็š„ๆ•ธๅญ—็š„ๅ€‹ๆ•ธ๏ผŒ ไพ‹ๅฆ‚๏ผš A[0] = -5 A[1] = -3 A[2] = -1 A[3] = 0 A[4] = 3 A[5] = 6 ็ต•ๅฐๅ€ผไธๅŒ็š„ๆ•ธ็š„ๅ€‹ๆ•ธ็‚บ 5๏ผŒ ๅ› ็‚บๅ…ถไธญๆœ‰ 5 ๅ€‹ไธๅŒ็š„็ต•ๅฐๅ€ผ๏ผš 0, 1, 3, 5, 6 ็ทจๅฏซไธ€ๅ€‹ๅ‡ฝๆ•ธ๏ผš func Solution(A []int) int ่ซ‹่ฟ”ๅ›ž็ตฆๅฎšๆœ‰ๅบๆ•ธ็ต„ไธญ็ต•ๅฐๅ€ผไธๅŒ็š„ๆ•ธ็š„ๅ€‹ๆ•ธใ€‚ ไพ‹ๅฆ‚๏ผŒ็ตฆๅ‡บๆ•ธ็ต„A๏ผš A[0] = -5 A[1] = -3 A[2] = -1 A[3] = 0 A[4] = 3 A[5] = 6 ๅ‡ฝๆ•ธๆ‡‰่ฟ”ๅ›ž5ใ€‚ ๅ‡ๅฎš: N ๆ˜ฏ [1..100,000] ๅ…ง็š„ ๆ•ดๆ•ธ; ๆ•ธ็ต„ A ๆฏๅ€‹ๅ…ƒ็ด ๆ˜ฏๅ–ๅ€ผ็ฏ„ๅœ [โˆ’2,147,483,648..2,147,483,647] ๅ…ง็š„ ๆ•ดๆ•ธ ; ๆ•ธ็ต„ A ๆ˜ฏ ้ž-้žๅขž ๅบๅˆ—. ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://app.codility.com/programmers/lessons/15-caterpillar_method/abs_distinct/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/AbsDistinct.go ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/":{"url":"GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/","title":"0031.Find-Minimum-Difference-Between-Any-Two-Elements","keywords":"","body":"0031. Find Minimum Difference Between Any Two Elements ้กŒ็›ฎ Given an unsorted array, find the minimum difference between any pair in given array. Examples : Input : {1, 5, 3, 19, 18, 25}; Output : 1 Minimum difference is between 18 and 19 Input : {30, 5, 20, 9}; Output : 4 Minimum difference is between 5 and 9 Input : {1, 19, -4, 31, 38, 25, 100}; Output : 5 Minimum difference is between 1 and -4 ไพ†ๆบ https://www.geeksforgeeks.org/find-minimum-difference-pair/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/Find-Minimum-Difference-Between-Any-Two-Elements.go package findminimumdifferencebetweenanytwoelements import ( \"math\" \"sort\" ) /* https://yourbasic.org/golang/absolute-value-int-float/ http://cavaliercoder.com/blog/optimized-abs-for-int64-in-go.html fmt.Println(abs(math.MinInt64)) // Output: -9223372036854775808 // ไผผไนŽๆฏ”่ผƒๅฟซ func WithTwosComplement(n int64) int64 { y := n >> 63 // y โ† x โŸซ 63 return (n ^ y) - y // (x โจ y) - y } */ func abs(n int) int { if n > 63 // y โ† x โŸซ 63 return (n ^ y) - y // (x โจ y) - y } // O(n Log n) func FindMinDiff(nums []int) int { if len(nums) tmp { minSize = tmp } } if minSize == math.MaxInt32 { minSize = 0 } return minSize } func FindMinDiff2(nums []int) int { if len(nums) tmp { minSize = tmp } } if minSize == math.MaxInt32 { minSize = 0 } return minSize } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0000.xxxx/":{"url":"Leetcode/0000.xxxx/","title":"NUM.LEETCODETITLE","summary":"NUM.FOLDERPATH","keywords":"","body":"NUM.LEETCODETITLE tagsstart LeetCode Go Easy/Medium/Hard LEETCODETITLE tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : `` ็ฉบ้–“่ค‡้›œ : `` ไพ†ๆบ LEETCODELINK https://leetcode.cn/problems/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/NUM.FOLDERPATH/main.go Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0001.Two-Sum/Merging-2-Packages/":{"url":"Leetcode/0001.Two-Sum/Merging-2-Packages/","title":"Merging 2 Packages","keywords":"","body":"Given a package with a weight limit limit and an array arr of item weights, implement a function getIndicesOfItemWeights that finds two items whose sum of weights equals the weight limit. The function should return a pair [i, j] of the indices of the item weights, ordered such that i > j. If such a pair doesnโ€™t exist, return an empty array. input: arr = [4, 6, 10, 15, 16], lim = 21 output: [3, 1] # since these are the indices of the weights 6 and 15 whose sum equals to 21 ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0001.Two-Sum/":{"url":"Leetcode/0001.Two-Sum/","title":"0001.Two Sum","summary":null,"keywords":"","body":"1. Two Sum tagsstart Easy tagsstop ้ข˜็›ฎ Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. ้กŒ็›ฎๅคงๆ„ ๅœจๆ•ธ็ต„ไธญๆ‰พๅˆฐ 2 ๅ€‹ๆ•ธไน‹ๅ’Œ็ญ‰ๆ–ผ็ตฆๅฎšๅ€ผ็š„ๆ•ธๅญ—, ็ตๆžœ่ฟ”ๅ›ž 2 ๅ€‹ๆ•ธๅญ—ๅœจๆ•ธ็ต„ไธญ็š„ไธ‹ๆจ™. ่งฃ้กŒๆ€่ทฏ ๆšดๅŠ›่งฃ: ๆ™‚้–“่ค‡้›œ O(n^2), ็ฉบ้–“่ค‡้›œ O(1) ้€™้“้กŒๆœ€ๅ„ช็š„ๅšๆณ•ๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏ O(n) ้ †ๅบๆŽƒๆๆ•ธ็ต„, ๅฐๆฏไธ€ๅ€‹ๅ…ƒ็ด ๏ผŒๅœจ map ไธญๆ‰พ่ƒฝ็ต„ๅˆ็ตฆๅฎšๅ€ผ็š„ๅฆไธ€ๅŠๆ•ธๅญ—, ๅฆ‚ๆžœๆ‰พๅˆฐไบ†, ็›ดๆŽฅ่ฟ”ๅ›ž 2 ๅ€‹ๆ•ธๅญ—็š„ไธ‹ๆจ™ๅณๅฏ. ๅฆ‚ๆžœๆ‰พไธๅˆฐ, ๅฐฑๆŠŠ้€™ๅ€‹ๆ•ธๅญ—ๅญ˜ๅ…ฅ map ไธญ, ็ญ‰ๅพ…ๆŽƒๅˆฐโ€œๅฆไธ€ๅŠโ€ๆ•ธๅญ—็š„ๆ™‚ๅ€™, ๅ†ๅ–ๅ‡บไพ†่ฟ”ๅ›ž็ตๆžœ. ๅฆ‚ๆžœnumsๆ˜ฏๆœ‰ๅบ ๅฏไปฅไฝฟ็”จๅทฆๅณๆŒ‡้‡ ไพ†ๆบ https://leetcode-cn.com/problems/two-sum/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0001.Two-Sum/twosum.go package twosum // ๆ™‚้–“่ค‡้›œ O(n^2), ็ฉบ้–“่ค‡้›œ O(1) func Twosum(nums []int, target int) []int { for i, _ := range nums { for j := i + 1; j target { // right-- // } // } // return []int{0, 0} // } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0002.Add-Two-Numbers/":{"url":"Leetcode/0002.Add-Two-Numbers/","title":"0002.Add Two Numbers","summary":"0002.Add-Two-Numbers","keywords":"","body":"0002.Add Two Numbers tagsstart LeetCode Go Medium Add Two Numbers Linked List Math Recursion Amazon Apple Facebook Microsoft Bloomberg tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ้ˆ่กจ้›™ๆŒ‡ๆจ™ๆŠ€ๅทง ๅ’ŒๅŠ ๆณ•้‹็ฎ—้Ž็จ‹ไธญๅฐ้€ฒไฝ็š„่™•็†ใ€‚ ๆณจๆ„้€™ๅ€‹ carry ่ฎŠๆ•ธ็š„่™•็†๏ผŒๅœจๆˆ‘ๅ€‘ๆ‰‹ๅ‹•้กžๆฏ”ๅŠ ๆณ•้Ž็จ‹็š„ๆ™‚ๅ€™ๆœƒ็ถ“ๅธธ็”จๅˆฐใ€‚ ้ๆญท l1่ทŸ l2. ่ฌ›ๅ…ฉๅ€‹list็š„val็›ธๅŠ , ไธฆไธ”่จ˜้Œ„้€ฒไฝ็š„ๅ€ผ็ตฆnextไฝฟ็”จ ๆœ€ๅพŒๅฆ‚ๆžœ carry ้‚„ๆœ‰็š„่ฉฑ, ้œ€่ฆ็”ข็”Ÿไธ€ๅ€‹ๆ–ฐ็š„็ฏ€้ปž Big O ๆ™‚้–“่ค‡้›œ : O(maxโก(m,n) ๆ™‚้–“่ค‡้›œๅบฆ๏ผš O(maxโก(m,n)) ๏ผŒๅ…ถไธญ m ๅ’Œ n ๅˆ†ๅˆฅ็‚บๅ…ฉๅ€‹้ˆ่กจ็š„้•ทๅบฆใ€‚ ๆˆ‘ๅ€‘่ฆ้ๆญทๅ…ฉๅ€‹้ˆ่กจ็š„ๅ…จ้ƒจไฝ็ฝฎ๏ผŒ่€Œ่™•็†ๆฏๅ€‹ไฝ็ฝฎๅช้œ€่ฆ O(1) ็š„ๆ™‚้–“ ็ฉบ้–“่ค‡้›œ : O(1) O(1) ใ€‚ ๆณจๆ„่ฟ”ๅ›žๅ€ผไธ่จˆๅ…ฅ็ฉบ้–“่ค‡้›œๅบฆ ไพ†ๆบ https://leetcode.com/problems/add-two-numbers/description/ https://leetcode.cn/problems/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0002.Add-Two-Numbers/main.go package addtwonumbers // ๆ™‚้–“่ค‡้›œ O(max(m,n)), ็ฉบ้–“่ค‡้›œ O(1) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ // ้ๆญท l1่ทŸ l2. ่ฌ›ๅ…ฉๅ€‹list็š„val็›ธๅŠ , ไธฆไธ”่จ˜้Œ„้€ฒไฝ็š„ๅ€ผ็ตฆnextไฝฟ็”จ // ๆœ€ๅพŒๅฆ‚ๆžœ carry ้‚„ๆœ‰็š„่ฉฑ, ้œ€่ฆ็”ข็”Ÿไธ€ๅ€‹ๆ–ฐ็š„็ฏ€้ปž func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { var result, tail *ListNode carry := 0 for l1 != nil || l2 != nil { n1, n2 := 0, 0 if l1 != nil { n1 = l1.Val l1 = l1.Next } if l2 != nil { n2 = l2.Val l2 = l2.Next } sum := n1 + n2 + carry sum, carry = sum%10, sum/10 if result == nil { result = &ListNode{Val: sum, Next: nil} tail = result } else { tail.Next = &ListNode{Val: sum, Next: nil} tail = tail.Next } } // ๆœ€ๅพŒๅฆ‚ๆžœ carry ้‚„ๆœ‰็š„่ฉฑ, ้œ€่ฆ็”ข็”Ÿไธ€ๅ€‹ๆ–ฐ็š„็ฏ€้ปž if carry > 0 { tail.Next = &ListNode{Val: carry, Next: nil} } return result } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0003.Longest-Substring-Without-Repeating-Characters/":{"url":"Leetcode/0003.Longest-Substring-Without-Repeating-Characters/","title":"0003.Longest Substring Without Repeating Characters","summary":"0003.Longest Substring Without Repeating Characters","keywords":"","body":"3. Longest Substring Without Repeating Characters tagsstart LeetCode Go Medium Longest Substring Without Repeating Characters Sliding Window Array tagsstop ้ข˜็›ฎ Given a string, find the length of the longest substring without repeating characters. Example 1: Input: \"abcabcbb\" Output: 3 Explanation: The answer is \"abc\", with the length of 3. Example 2: Input: \"bbbbb\" Output: 1 Explanation: The answer is \"b\", with the length of 1. Example 3: Input: \"pwwkew\" Output: 3 Explanation: The answer is \"wke\", with the length of 3. Note that the answer must be a substring, \"pwke\" is a subsequence and not a substring. ้กŒ็›ฎๅคงๆ„ ๅœจไธ€ๅ€‹ๅญ—็ฌฆไธฒ้‡ๅฐ‹ๆ‰พๆฒ’ๆœ‰้‡่ค‡ๅญ—ๆฏ็š„ๆœ€้•ทๅญไธฒใ€‚ ่งฃ้กŒๆ€่ทฏ ้€™ไธ€้กŒๅ’Œ็ฌฌ 438 ้กŒ๏ผŒ็ฌฌ 3 ้กŒ๏ผŒ็ฌฌ 76 ้กŒ๏ผŒ็ฌฌ 567 ้กŒ้กžไผผ๏ผŒ็”จ็š„ๆ€ๆƒณ้ƒฝๆ˜ฏ\"ๆป‘ๅ‹•็ช—ๅฃ\"ใ€‚ ๆป‘ๅ‹•็ช—ๅฃ็š„ๅณ้‚Š็•Œไธๆ–ท็š„ๅณ็งป๏ผŒๅช่ฆๆฒ’ๆœ‰้‡่ค‡็š„ๅญ—็ฌฆ๏ผŒๅฐฑๆŒ็บŒๅ‘ๅณๆ“ดๅคง็ช—ๅฃ้‚Š็•Œใ€‚ไธ€ๆ—ฆๅ‡บ็พไบ†้‡่ค‡ๅญ—็ฌฆ๏ผŒๅฐฑ้œ€่ฆ็ธฎๅฐๅทฆ้‚Š็•Œ๏ผŒ็›ดๅˆฐ้‡่ค‡็š„ๅญ—็ฌฆ็งปๅ‡บไบ†ๅทฆ้‚Š็•Œ๏ผŒ็„ถๅพŒ็นผ็บŒ็งปๅ‹•ๆป‘ๅ‹•็ช—ๅฃ็š„ๅณ้‚Š็•Œใ€‚ไปฅๆญค้กžๆŽจ๏ผŒๆฏๆฌก็งปๅ‹•้œ€่ฆ่จˆ็ฎ—็•ถๅ‰้•ทๅบฆ๏ผŒไธฆๅˆคๆ–ทๆ˜ฏๅฆ้œ€่ฆๆ›ดๆ–ฐๆœ€ๅคง้•ทๅบฆ๏ผŒๆœ€็ต‚ๆœ€ๅคง็š„ๅ€ผๅฐฑๆ˜ฏ้กŒ็›ฎไธญ็š„ๆ‰€ๆฑ‚ใ€‚ O(n) ็”จ็ฉบ้–“ๆ›ๅ–ๆ™‚้–“, map็ด€้Œ„ๅทฒๅ‡บ็พ้Ž็š„ๅญ—็ฌฆ, ๅฆ‚ๆžœmapๆ•ˆ่ƒฝไธๅฅฝๆ™‚ๅฏไฝฟ็”จๆ•ธ็ต„(Slice)ไพ†ๆ”นๅ–„ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0003.Longest-Substring-Without-Repeating-Characters/ https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/Longest-Substring-Without-Repeating-Characters.go package longestSubstringwithoutrepeatingcharacters // LengthOfLongestSubstring ๆšดๅŠ›่งฃ func LengthOfLongestSubstring(s string) int { slength := len(s) if slength == 0 || slength == 1 { return slength } tmpLen := 1 var maxLen = 1 for i := 1; i maxLen { maxLen = tmpLen } } return maxLen } // LengthOfLongestSubstringMap ็”จmap ็ด€้Œ„ๆ˜ฏๅฆ้‡่ค‡. func LengthOfLongestSubstringMap(s string) int { slength := len(s) if slength == 0 || slength == 1 { return slength } charMap := make(map[byte]bool) maxLen, left, right := 0, 0, 0 for left = slength || right >= len(s) { break } } return maxLen } // LengthOfLongestSubstringBit ็”จmapๆ•ˆ่ƒฝไธๅฅฝๆ™‚ๅฏไฝฟ็”จๆ•ธ็ต„ๆ”นๅ–„ func LengthOfLongestSubstringBit(s string) int { slength := len(s) if slength == 0 || slength == 1 { return slength } // ASCII 0~255 charMap := [256]bool{} maxLen, left, right := 0, 0, 0 for left = slength || right >= len(s) { break } } return maxLen } Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkLengthOfLongestSubstring-8 66143602 19.08 ns/op 0 B/op 0 allocs/op BenchmarkLengthOfLongestSubstringMap-8 2524627 397.8 ns/op 0 B/op 0 allocs/op BenchmarkLengthOfLongestSubstringBit-8 65099846 21.37 ns/op 0 B/op 0 allocs/op PASS ok LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters 4.193s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0005.Longest-Palindromic-Substring/":{"url":"Leetcode/0005.Longest-Palindromic-Substring/","title":"0005. Longest Palindromic Substring","summary":"0005. Longest Palindromic Substring","keywords":"","body":"0005.Longest Palindromic Substring tagsstart LeetCode Go Medium DP Amazon Microsoft Google Adobe Facebook tagsstop ้กŒ็›ฎ Given a string s, return the longest palindromic substring in s. A string is called a palindrome string if the reverse of that string is the same as the original string. Example 1: Input: s = \"babad\" Output: \"bab\" Explanation: \"aba\" is also a valid answer. Example 2: Input: s = \"cbbd\" Output: \"bb\" Constraints: 1 s consist of only digits and English letters. ้กŒ็›ฎๅคงๆ„ ็ตฆไฝ ไธ€ๅ€‹ๅญ—็ฌฆไธฒ s๏ผŒๆ‰พๅˆฐ s ไธญๆœ€้•ท็š„ๅ›žๆ–‡ๅญไธฒใ€‚ ่งฃ้กŒๆ€่ทฏ ๆฏไธ€ๅ€‹ๅญ—็ฌฆๆœฌ่บซ้ƒฝๆ˜ฏๅ›žๆ–‡ ้•ทๅบฆ็‚บ 2, ไธ”้ฆ–ๅฐพๅญ—็ฌฆ็›ธๅŒๅ‰‡็‚บๅ›žๆ–‡ ้•ทๅบฆ>=3, ๅฆ‚ๆžœ้ ญๅฐพ็›ธๅŒ, ๅ‰‡ๅŽปๆŽ‰้ ญๅฐพๅพŒๅฏ็œ‹ๆ˜ฏๅˆๆ˜ฏๅ›žๆ–‡. ๅฆ‚ๆžœ้ ญๅฐพไธๅŒๅ‰‡ไธๆ˜ฏๅ›žๆ–‡ ไพ†ๆบ https://leetcode.com/problems/longest-palindromic-substring/ https://leetcode.cn/problems/longest-palindromic-substring/solutions/1348874/s-by-xext-5zk3/ ่งฃ็ญ” package longestpalindromicsubstring func longestPalindrome(s string) string { dp := make([][]bool, len(s)) result := s[0:1] for i := 0; i len(result) { result = s[start : end+1] } } } return result } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0015.3Sum/":{"url":"Leetcode/0015.3Sum/","title":"0015. 3Sum","summary":"0015.3Sum","keywords":"","body":"15. 3Sum tagsstart LeetCode Go Medium 3Sum Array Two Pointers Sorting tagsstop ้กŒ็›ฎ Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Note: The solution set must not contain duplicate triplets. Example: Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ] ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆ•ธ็ต„๏ผŒ่ฆๆฑ‚ๅœจ้€™ๅ€‹ๆ•ธ็ต„ไธญๆ‰พๅ‡บ 3 ๅ€‹ๆ•ธไน‹ๅ’Œ็‚บ 0 ็š„ๆ‰€ๆœ‰็ต„ๅˆใ€‚ ่งฃ้กŒๆ€่ทฏ ็”จ map ๆๅ‰่จˆ็ฎ—ๅฅฝไปปๆ„ 2 ๅ€‹ๆ•ธๅญ—ไน‹ๅ’Œ๏ผŒไฟๅญ˜่ตทไพ†๏ผŒๅฏไปฅๅฐ‡ๆ™‚้–“่ค‡้›œๅบฆ้™ๅˆฐ O(n^2)ใ€‚้€™ไธ€้กŒๆฏ”่ผƒ้บป็…ฉ็š„ไธ€้ปžๅœจๆ–ผ๏ผŒๆœ€ๅพŒ่ผธๅ‡บ่งฃ็š„ๆ™‚ๅ€™๏ผŒ่ฆๆฑ‚่ผธๅ‡บไธ้‡่ค‡็š„่งฃใ€‚ๆ•ธ็ต„ไธญๅŒไธ€ๅ€‹ๆ•ธๅญ—ๅฏ่ƒฝๅ‡บ็พๅคšๆฌก๏ผŒๅŒไธ€ๅ€‹ๆ•ธๅญ—ไนŸๅฏ่ƒฝไฝฟ็”จๅคšๆฌก๏ผŒไฝ†ๆ˜ฏๆœ€ๅพŒ่ผธๅ‡บ่งฃ็š„ๆ™‚ๅ€™๏ผŒไธ่ƒฝ้‡่ค‡ใ€‚ไพ‹ๅฆ‚[-1๏ผŒ-1๏ผŒ2] ๅ’Œ[2, -1, -1]ใ€[-1, 2, -1] ้€™3 ๅ€‹่งฃๆ˜ฏ้‡่ค‡็š„๏ผŒๅณไฝฟ-1 ๅฏ่ƒฝๅ‡บ็พ100 ๆฌก๏ผŒๆฏๆฌกไฝฟ็”จ็š„-1 ็š„ๆ•ธ็ต„ไธ‹ๆจ™้ƒฝๆ˜ฏไธๅŒ็š„ใ€‚ ้€™่ฃกๅฐฑ้œ€่ฆๅŽป้‡ๅ’ŒๆŽ’ๅบไบ†ใ€‚ map ่จ˜้Œ„ๆฏๅ€‹ๆ•ธๅญ—ๅ‡บ็พ็š„ๆฌกๆ•ธ๏ผŒ็„ถๅพŒๅฐ map ็š„ key ๆ•ธ็ต„้€ฒ่กŒๆŽ’ๅบ๏ผŒๆœ€ๅพŒๅœจ้€™ๅ€‹ๆŽ’ๅบไปฅๅพŒ็š„ๆ•ธ็ต„่ฃก้ขๆŽƒ๏ผŒๆ‰พๅˆฐๅฆๅค– 2 ๅ€‹ๆ•ธๅญ—่ƒฝๅ’Œ่‡ชๅทฑ็ต„ๆˆ 0 ็š„็ต„ๅˆใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0015.3Sum/ https://leetcode-cn.com/problems/3sum/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0015.3Sum/3Sum.go package threesum import ( \"sort\" ) // ThreeSumBurst : ๆšดๅŠ›่งฃ : O(n^3) func ThreeSumBurst(nums []int) [][]int { result := [][]int{} sort.Ints(nums) // O(n log n) for i := 0; i 0 && nums[i] == nums[i-1] { continue } for j := i + 1; j i+1 && nums[j] == nums[j-1] { continue } for k := j + 1; k 1 && nums[i] == nums[i-1] { // ๅŽปๆŽ‰้‡่ค‡ start = i - 1 } for start i { if start > 0 && nums[start] == nums[start-1] { // ๅŽปๆŽ‰้‡่ค‡ start++ continue } if end 0 { end-- } else { start++ } } } return result } func ThreeSumHashTable(nums []int) [][]int { result := [][]int{} if len(nums) 0 && nums[i] == nums[i-1] { continue } seen := make(map[int]bool) target := -nums[i] // ็›ฎๆจ™ๅ€ผ็‚บ็•ถๅ‰ๅ…ƒ็ด ็š„็›ธๅๆ•ธ for j := i + 1; j 0 && nums[i] == nums[i-1] { continue } target, l, r := -nums[i], i+1, len(nums)-1 for l target { r-- } else if sum goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0015.3Sum cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz BenchmarkThreeSumBurst-4 9838000 121.4 ns/op 48 B/op 2 allocs/op BenchmarkThreeSumDoublePoint-4 9069201 112.8 ns/op 48 B/op 2 allocs/op BenchmarkThreeSumHashTable-4 7935907 147.1 ns/op 48 B/op 2 allocs/op BenchmarkThreeSumTwoPointer-4 10888315 103.5 ns/op 48 B/op 2 allocs/op PASS ok LeetcodeGolang/Leetcode/0015.3Sum 5.055s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0019.Remove-Nth-Node-From-End-of-List/":{"url":"Leetcode/0019.Remove-Nth-Node-From-End-of-List/","title":"0019. Remove Nth Node From End of List","summary":"0015.3Sum","keywords":"","body":"19. Remove Nth Node From End of List tagsstart LeetCode Go Medium Linked List Two Pointers Facebook Amazon Microsoft Google Bloomberg tagsstop ้กŒ็›ฎ Given the head of a linked list, remove the nth node from the end of the list and return its head. Example 1: Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5] Example 2: Input: head = [1], n = 1 Output: [] Example 3: Input: head = [1,2], n = 1 Output: [1] Constraints: The number of nodes in the list is sz. 1 0 1 ้กŒ็›ฎๅคงๆ„ ๆ‰พๅฐ‹ๅ–ฎlinked list็š„ ๅ€’ๆ•ธ็ฌฌ n ๅ€‹ๅ…ƒ็ด ไธฆๅˆช้™ค. ่ฟ”ๅ›ž่ฉฒ linked list็š„้ ญ็ฏ€้ปž ่งฃ้กŒๆ€่ทฏ ๅ…ˆ่ฎ“ fast่ตฐ k ๆญฅ, ็„ถๅพŒ fast slow ๅŒ้€Ÿๅ‰้€ฒ ้€™ๆจฃ็•ถfast่ตฐๅˆฐnilๆ™‚, slowๆ‰€ๅœจไฝ็ฝฎๅฐฑๆ˜ฏๅœจๅ€’ๆ•ธ็ฌฌ k ็š„็ฏ€้ปž ไพ†ๆบ https://leetcode.com/problems/remove-nth-node-from-end-of-list/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0019.Remove-Nth-Node-From-End-of-List/main.go package removenthnodefromendoflist /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } // ็”ข็”Ÿ dummyHead,่ทŸ preslow // ไฝฟ็”จ้›™ๆŒ‡้‡, ๅ…ˆ่ฎ“ fast่ตฐ `k` ๆญฅ, ็„ถๅพŒ `fast slow ๅŒ้€Ÿๅ‰้€ฒ` // ้€™ๆจฃ็•ถfast่ตฐๅˆฐnilๆ™‚, slowๆ‰€ๅœจไฝ็ฝฎๅฐฑๆ˜ฏๅœจๅ€’ๆ•ธ็ฌฌ k ็š„็ฏ€้ปž // ๅฐ‡ slow็š„ๅ‰ไธ€ๆญฅ(preslow)็š„next ๆŒ‡ๅ‘ slow.Next func RemoveNthFromEnd(head *ListNode, n int) *ListNode { dummyHead := &ListNode{Next: head} preSlow, slow, fast := dummyHead, head, head for fast != nil { if n tags: Medium Leetcode Two Pointers ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0020.Valid-Parentheses/":{"url":"Leetcode/0020.Valid-Parentheses/","title":"0020. Valid Parentheses","summary":"0020.Valid-Parentheses","keywords":"","body":"0020. Valid Parentheses tagsstart LeetCode Go Easy Valid Parentheses tagsstop ้กŒ็›ฎ Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type. Example 1: Input: s = \"()\" Output: true Example 2: Input: s = \"()[]{}\" Output: true Example 3: Input: s = \"(]\" Output: false Constraints: 1 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : ็ฉบ้–“่ค‡้›œ : ไพ†ๆบ https://leetcode.com/problems/valid-parentheses/ https://leetcode.cn/problems/valid-parentheses/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0020.Valid-Parentheses/main.go package validparentheses type Stack struct { runes []rune } func NewStack() *Stack { return &Stack{runes: []rune{}} } func (s *Stack) Push(str rune) { s.runes = append(s.runes, str) } func (s *Stack) Pop() rune { str := s.runes[len(s.runes)-1] s.runes = s.runes[:len(s.runes)-1] return str } // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(n) func IsValid(s string) bool { runeStack := NewStack() for _, v := range s { // fmt.Println(string(v)) if v == '(' || v == '[' || v == '{' { runeStack.Push(v) } else if (v == ')' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '(') || (v == ']' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '[') || (v == '}' && len(runeStack.runes) > 0 && runeStack.runes[len(runeStack.runes)-1] == '{') { runeStack.Pop() } else { return false } } return len(runeStack.runes) == 0 } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0021.Merge-Two-Sorted-Lists/":{"url":"Leetcode/0021.Merge-Two-Sorted-Lists/","title":"0021. Merge Two Sorted Lists","summary":"0021.Merge-Two-Sorted-Lists","keywords":"","body":"0021. Merge Two Sorted Lists tagsstart LeetCode Go Easy/Medium/Hard Merge Two Sorted Lists tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : O( log n) ็ฉบ้–“่ค‡้›œ : O(1) ไพ†ๆบ https://leetcode.com/problems/merge-two-sorted-lists/description/ https://leetcode.cn/problems/merge-two-sorted-lists/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0021.Merge-Two-Sorted-Lists/main.go package mergetwosortedlists type ListNode struct { Val int Next *ListNode } // ๆ™‚้–“่ค‡้›œ O(log n), ็ฉบ้–“่ค‡้›œ O(1) func MergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { head := &ListNode{Next: nil} cur := head for list1 != nil && list2 != nil { if list1.Val Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0027.Remove-Element/":{"url":"Leetcode/0027.Remove-Element/","title":"0027.Remove Element","summary":null,"keywords":"","body":"27. Remove Element tagsstart Easy Array tagsstop ้กŒ็›ฎ Given an array nums and a value val, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. The order of elements can be changed. It doesn't matter what you leave beyond the new length. Example 1: Given nums = [3,2,2,3], val = 3, Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. Clarification: Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆ•ธ็ต„ nums ๅ’Œไธ€ๅ€‹ๆ•ธๅ€ผ val๏ผŒๅฐ‡ๆ•ธ็ต„ไธญๆ‰€ๆœ‰็ญ‰ๆ–ผ val ็š„ๅ…ƒ็ด ๅˆช้™ค๏ผŒไธฆ่ฟ”ๅ›žๅ‰ฉ้ค˜็š„ๅ…ƒ็ด ๅ€‹ๆ•ธใ€‚ ่งฃ้กŒๆ€่ทฏ ้€™้“้กŒๅ’Œ็ฌฌ 283 ้กŒๅพˆๅƒใ€‚้€™้“้กŒๅ’Œ็ฌฌ 283 ้กŒๅŸบๆœฌไธ€่‡ด๏ผŒ283 ้กŒๆ˜ฏๅˆช้™ค 0๏ผŒ้€™ไธ€้กŒๆ˜ฏ็ตฆๅฎš็š„ไธ€ๅ€‹ val๏ผŒๅฏฆ่ณชๆ˜ฏไธ€ๆจฃ็š„ใ€‚ ้€™้‡Œๆ•ธ็ต„็š„ๅˆช้™คไธฆไธๆ˜ฏ็œŸ็š„ๅˆช้™ค๏ผŒๅชๆ˜ฏๅฐ‡ๅˆช้™ค็š„ๅ…ƒ็ด ็งปๅ‹•ๅˆฐๆ•ธ็ต„ๅพŒ้ข็š„็ฉบ้–“ๅ…ง๏ผŒ็„ถๅพŒ่ฟ”ๅ›žๆ•ธ็ต„ๅฏฆ้š›ๅ‰ฉ้ค˜็š„ๅ…ƒ็ด ๅ€‹ๆ•ธ๏ผŒOJ ๆœ€็ต‚ๅˆคๆ–ท้กŒ็›ฎ็š„ๆ™‚ๅ€™ๆœƒ่ฎ€ๅ–ๆ•ธ็ต„ๅ‰ฉ้ค˜ๅ€‹ๆ•ธ็š„ๅ…ƒ็ด ้€ฒ่กŒ่ผธๅ‡บใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0027.Remove-Element/ https://leetcode-cn.com/problems/remove-element/ https://mp.weixin.qq.com/s/wj0T-Xs88_FHJFwayElQlA ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0027.Remove-Element/Remove-Element.go package removeelement /* ้›™ๆŒ‡้‡ๆณ• ้›™ๆŒ‡้‡ๆณ•๏ผˆๅฟซๆ…ขๆŒ‡้‡ๆณ•๏ผ‰ๅœจๆ•ธ็ต„ๅ’Œ้Š้Œถ็š„ๆ“ไฝœไธญๆ˜ฏ้žๅธธๅธธ่ฆ‹็š„๏ผŒๅพˆๅคš่€ƒๅฏŸๆ•ธ็ต„ๅ’Œ้Š้Œถๆ“ไฝœ็š„้ข่ฉฆ้กŒ๏ผŒ้ƒฝไฝฟ็”จ้›™ๆŒ‡้‡ๆณ• */ func RemoveElementDoublePoint(nums []int, val int) int { if len(nums) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/":{"url":"Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/","title":"0028. Find the Index of the First Occurrence in a String","summary":"0028.Find-the-Index-of-the-First-Occurrence-in-a-String","keywords":"","body":"0028. Find the Index of the First Occurrence in a String tagsstart LeetCode Go Easy Find the Index of the First Occurrence in a String Two Pointers String String Matching tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : `` ็ฉบ้–“่ค‡้›œ : `` ไพ†ๆบ https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/ https://leetcode.cn/problems/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/main.go Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0035.Search-Insert-Position/":{"url":"Leetcode/0035.Search-Insert-Position/","title":"0035.Search Insert Position","summary":null,"keywords":"","body":"35. Search Insert Position tagsstart Easy Array tagsstop ้กŒ็›ฎ Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Example 1: Input: [1,3,5,6], 5 Output: 2 Example 2: Input: [1,3,5,6], 2 Output: 1 Example 3: Input: [1,3,5,6], 7 Output: 4 Example 4: Input: [1,3,5,6], 0 Output: 0 ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆŽ’ๅบๆ•ธ็ต„ๅ’Œไธ€ๅ€‹็›ฎๆจ™ๅ€ผ๏ผŒๅœจๆ•ธ็ต„ไธญๆ‰พๅˆฐ็›ฎๆจ™ๅ€ผ๏ผŒไธฆ่ฟ”ๅ›žๅ…ถ็ดขๅผ•ใ€‚ๅฆ‚ๆžœ็›ฎๆจ™ๅ€ผไธๅญ˜ๅœจๆ–ผๆ•ธ็ต„ไธญ๏ผŒ่ฟ”ๅ›žๅฎƒๅฐ‡ๆœƒ่ขซๆŒ‰้ †ๅบๆ’ๅ…ฅ็š„ไฝ็ฝฎใ€‚ ไฝ ๅฏไปฅๅ‡่จญๆ•ธ็ต„ไธญ็„ก้‡่ค‡ๅ…ƒ็ด ใ€‚ ่งฃ้กŒๆ€่ทฏ ็ตฆๅ‡บไธ€ๅ€‹ๅทฒ็ถ“ๅพžๅฐๅˆฐๅคงๆŽ’ๅบๅพŒ็š„ๆ•ธ็ต„๏ผŒ่ฆๆฑ‚ๅœจๆ•ธ็ต„ไธญๆ‰พๅˆฐๆ’ๅ…ฅ target ๅ…ƒ็ด ็š„ไฝ็ฝฎใ€‚ ้€™ไธ€้กŒๆ˜ฏ็ถ“ๅ…ธ็š„ไบŒๅˆ†ๆœ็ดข็š„่ฎŠ็จฎ้กŒ๏ผŒๅœจๆœ‰ๅบๆ•ธ็ต„ไธญๆ‰พๅˆฐๆœ€ๅพŒไธ€ๅ€‹ๆฏ” target ๅฐ็š„ๅ…ƒ็ด ใ€‚ \b- ๅช่ฆ็œ‹ๅˆฐ้ข่ฉฆ้กŒ่ฃก็ตฆๅ‡บ็š„ๆ•ธ็ต„ๆ˜ฏๆœ‰ๅบๆ•ธ็ต„๏ผŒ้ƒฝๅฏไปฅๆƒณไธ€ๆƒณๆ˜ฏๅฆๅฏไปฅไฝฟ็”จไบŒๅˆ†ๆณ• ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0035.Search-Insert-Position/ https://leetcode-cn.com/problems/search-insert-position/ ๆ•ธ็ต„๏ผšๆฏๆฌก้‡ๅˆฐไบŒๅˆ†ๆณ•๏ผŒ้ƒฝๆ˜ฏไธ€็œ‹ๅฐฑๆœƒ๏ผŒไธ€ๅฏซๅฐฑๅปข ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0035.Search-Insert-Position/Search-Insert-Position.go package searchinsertposition // ๆšดๅŠ›่งฃ ๆ™‚้–“่ค‡้›œ O(n) ็ฉบ้–“่ค‡้›œ O(1) func SearchInsertBurst(nums []int, target int) int { for i := 0; i = target { return i } } return len(nums) } //ไบŒๅˆ†ๆณ• ๆ™‚้–“่ค‡้›œ O(log n) ็ฉบ้–“่ค‡้›œ O(1) func SearchInsertBisection(nums []int, target int) int { left, right := 0, len(nums)-1 for left >1 if nums[mid] >= target { right = mid - 1 } else if nums[mid] >1 if nums[mid] >= target { right = mid - 1 } else { left = mid + 1 } } return left } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0046.Permutations/":{"url":"Leetcode/0046.Permutations/","title":"0046.Permutations","summary":null,"keywords":"","body":"46. Permutations tagsstart Medium Backtracking tagsstop ้กŒ็›ฎ Given a collection of distinct integers, return all possible permutations(ๆŽ’ๅˆ—). Example: Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ] ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆฒ’ๆœ‰้‡่ค‡ๆ•ธๅญ—็š„ๅบๅˆ—๏ผŒ่ฟ”ๅ›žๅ…ถๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ๅ…จๆŽ’ๅˆ—ใ€‚ ่งฃ้กŒๆ€่ทฏ ่งฃๆฑบๅ›žๆœ”ๅ•้กŒๅฏ็”จไธ€ๅ€‹ๆฑบ็ญ–ๆจน็š„้ๆญท้Ž็จ‹ ่ทฏๅพ‘: ไนŸๅฐฑๆ˜ฏๅทฒ็ถ“ๅš็š„้ธๆ“‡ ้ธๆ“‡ๅˆ—่กจ: ไนŸๅฐฑๆ˜ฏ็•ถๅ‰ๅฏไปฅๅš็š„้ธๆ“‡ ็ตๆŸๆขไปถ: ไนŸๅฐฑๆ˜ฏ้”ๅˆฐๆฑบ็ญ–ๆจนๅบ•ๅฑค, ็„กๆณ•ๅ†ๅš้ธๆ“‡็š„ๆขไปถ result = [] def backtrack(่ทฏๅพ‘, ้ธๆ“‡ๅˆ—่กจ): if ๆปฟ่ถณ็ตๆŸๆขไปถ: result.add(่ทฏๅพ‘) return for ้ธๆ“‡ in ้ธๆ“‡ๅˆ—่กจ: ๅš้ธๆ“‡ backtrack(่ทฏๅพ‘, ้ธๆ“‡ๅˆ—่กจ) ๆ’ค้Šท้ธๆ“‡ ้ธๆ“‡:[1,2,3] [] [1]/ |[2] \\[3] [2]/ \\[3] [1]/ \\[3] [1]/ \\[2] |[3] |[2] |[3] |[1] |[2] |[1] ็ตๆžœ [1,2,3] [1,3,2] [2,1,3] [2,3,1] [3,1,2] [3,2,1] ๆฑ‚ๅ‡บไธ€ๅ€‹ๆ•ธ็ต„็š„ๆŽ’ๅˆ—็ต„ๅˆไธญ็š„ๆ‰€ๆœ‰ๆŽ’ๅˆ—๏ผŒ็”จ DFS ๆทฑๆœๅณๅฏใ€‚ ้€™ๅ€‹ๅ•้กŒๅฏไปฅ็œ‹ไฝœๆœ‰ รฑ ๅ€‹ๆŽ’ๅˆ—ๆˆไธ€่กŒ็š„็ฉบๆ ผ๏ผŒๆˆ‘ๅ€‘้œ€่ฆๅพžๅทฆๅพ€ๅณไพๆญคๅกซๅ…ฅ้กŒ็›ฎ็ตฆๅฎš็š„ รฑๅ€‹ๆ•ธ๏ผŒๆฏๅ€‹ๆ•ธๅช่ƒฝไฝฟ็”จไธ€ๆฌกใ€‚ ้‚ฃ้บผๅพˆ็›ดๆŽฅ็š„ๅฏไปฅๆƒณๅˆฐไธ€็จฎ็ชฎ่ˆ‰็š„็ฎ—ๆณ•๏ผŒๅณๅพžๅทฆๅพ€ๅณๆฏไธ€ๅ€‹ไฝ็ฝฎ้ƒฝไพๆญคๅ˜—่ฉฆๅกซๅ…ฅไธ€ๅ€‹ๆ•ธ๏ผŒ ็œ‹่ƒฝไธ่ƒฝๅกซๅฎŒ้€™รฑ ๅ€‹็ฉบๆ ผ๏ผŒๅœจ็จ‹ๅบไธญๆˆ‘ๅ€‘ๅฏไปฅ็”จใ€Œๅ›žๆบฏๆณ•ใ€ไพ†ๆจกๆ“ฌ้€™ๅ€‹้Ž็จ‹ ๅ›žๆบฏๆณ•๏ผš ไธ€็จฎ้€š้ŽๆŽข็ดขๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ๅ€™้ธ่งฃไพ†ๆ‰พๅ‡บๆ‰€ๆœ‰็š„่งฃ็š„็ฎ—ๆณ•ใ€‚ๅฆ‚ๆžœๅ€™้ธ่งฃ่ขซ็ขบ่ชไธๆ˜ฏไธ€ๅ€‹่งฃ๏ผˆๆˆ–่€…่‡ณๅฐ‘ไธๆ˜ฏๆœ€ๅพŒไธ€ๅ€‹่งฃ๏ผ‰๏ผŒ ๅ›žๆบฏ็ฎ—ๆณ•ๆœƒ้€š้ŽๅœจไธŠไธ€ๆญฅ้€ฒ่กŒไธ€ไบ›่ฎŠๅŒ–ๆ‹‹ๆฃ„่ฉฒ่งฃ๏ผŒๅณๅ›žๆบฏไธฆไธ”ๅ†ๆฌกๅ˜—่ฉฆใ€‚ ไฝœ่€…๏ผšLeetCode-Solution ้“พๆŽฅ๏ผšhttps://leetcode-cn.com/problems/permutations/solution/quan-pai-lie-by-leetcode-solution-2/ ๆฅๆบ๏ผšๅŠ›ๆ‰ฃ๏ผˆLeetCode๏ผ‰ ่‘—ไฝœๆƒๅฝ’ไฝœ่€…ๆ‰€ๆœ‰ใ€‚ๅ•†ไธš่ฝฌ่ฝฝ่ฏท่”็ณปไฝœ่€…่Žทๅพ—ๆŽˆๆƒ๏ผŒ้žๅ•†ไธš่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๅ‡บๅค„ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0046.Permutations/ https://leetcode-cn.com/problems/permutations/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0046.Permutations/Permutations.go ๆ™‚้–“่ค‡้›œ O(n) package permutations func Permute(nums []int) [][]int { numsLen := len(nums) if numsLen == 0 { return [][]int{} } used, path, res := make([]bool, numsLen), []int{}, [][]int{} dfs(nums, numsLen, 0, path, &used, &res) return res } /* generatePermutation: (่ผธๅ…ฅๆ•ธ็ต„, ๆ•ธ็ต„้•ทๅบฆ, ้ž่ฟดๅˆฐ็ฌฌๅนพๅฑคdepth, path, ไฝฟ็”จ้Ž็š„, ็ตๆžœ) ๆ‰พๆœ€็Ÿญ่ทฏๅพ‘็”จ**BFS**, ๅ…ถไป–ๆ™‚็”จ**DFS**็”จๅพ—ๅคšไธ€ไบ›, ๅ› ็‚บ้ž่ฟด่ผƒๅฅฝๅฏซ ๅ‡่จญๆœ‰ๆฃตๆปฟ็š„ไบŒๅ‰ๆจน,็ฏ€้ปžๆ•ธ็‚บ N. ๅฐDFSไพ†่ชช็ฉบ้–“่ค‡้›œๅบฆๅฐฑๆ˜ฏ้ž่ฟด, ๆœ€ๅฃž็š„ๆƒ…ๆณๅฐฑๆ˜ฏๆจน็š„้ซ˜ๅบฆ O(log N) BFS็ฎ—ๆณ•, Queueๆฏๆฌก้ƒฝๆœƒๅญ˜ไบŒๅ‰ๆจนไธ€ๅฑค็š„็ฏ€้ปž, ๆœ€ๅฃž็š„ๆƒ…ๆณไธ‹็ฉบ้–“่ค‡้›œๅบฆๆ‡‰่ฉฒๅฐฑๆ˜ฏๆจน็š„ๆœ€ไธ‹ๅฑค็š„ๆ•ธ้‡, ไนŸๅฐฑๆ˜ฏ N/2. ็ฉบ้–“่ค‡้›œๅบฆ O(N) DFS๏ผˆๆทฑๅบฆๅ„ชๅ…ˆๆœ็ดข๏ผ‰้€šๅธธไฝฟ็”จๅ †ๆฃง๏ผˆStack๏ผ‰ไพ†ๅฏฆ็พใ€‚ๅœจDFSไธญ๏ผŒๆ‚จ้ฆ–ๅ…ˆ่™•็†ไธ€ๅ€‹็ฏ€้ปž๏ผŒ็„ถๅพŒๅฐ‡ๅ…ถๅญ็ฏ€้ปžๆŒ‰ๆŸ็จฎ้ †ๅบๆŽจๅ…ฅๅ †ๆฃงไธญ๏ผŒๆŽฅ่‘—็นผ็บŒ่™•็†ๅ †ๆฃง้ ‚้ƒจ็š„็ฏ€้ปž๏ผŒ็›ดๅˆฐๅ †ๆฃง็‚บ็ฉบใ€‚ */ func generatePermutation(nums []int, numsLen int, depth int, path []int, used *[]bool, res *[][]int) { if depth == numsLen { temp := make([]int, len(path)) copy(temp, path) *res = append(*res, temp) return } for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0049.Group-Anagrams/":{"url":"Leetcode/0049.Group-Anagrams/","title":"0049.Group Anagrams","summary":"Group Anagrams","keywords":"","body":"0049.Grop Anagrams tagsstart LeetCode Go Medium Group Anagrams tagsstop ้กŒ็›ฎ Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: strs = [\"eat\",\"tea\",\"tan\",\"ate\",\"nat\",\"bat\"] Output: [[\"bat\"],[\"nat\",\"tan\"],[\"ate\",\"eat\",\"tea\"]] Example 2: Input: strs = [\"\"] Output: [[\"\"]] Example 3: Input: strs = [\"a\"] Output: [[\"a\"]] Constraints: 1 0 strs[i] consists of lowercase English letters. ้กŒ็›ฎๅคงๆ„ ๅˆ†็ต„ๅ‡บๅช็”จๅŒๆจฃๅญ—็ฌฆ็”ข็”Ÿ็š„็š„ๅ–ฎๅญ— ่งฃ้กŒๆ€่ทฏ ๆ–นๆณ•ไธ€: ่จˆๆ•ธ ็”ฑๆ–ผไบ’็‚บๅญ—ๆฏ็•ฐไฝ่ฉž็š„ๅ…ฉๅ€‹ๅญ—ไธฒๅŒ…ๅซ็š„ๅญ—ๆฏ็›ธๅŒ๏ผŒๅ› ๆญคๅ…ฉๅ€‹ๅญ—ไธฒไธญ็š„็›ธๅŒๅญ—ๆฏๅ‡บ็พ็š„ๆฌกๆ•ธไธ€ๅฎšๆ˜ฏ็›ธๅŒ็š„๏ผŒๆ•…ๅฏไปฅๅฐ‡ๆฏๅ€‹ๅญ—ๆฏๅ‡บ็พ็š„ๆฌกๆ•ธไฝฟ็”จๅญ—ไธฒ่กจ็คบ๏ผŒไฝœ็‚บๅ“ˆๅธŒ่กจ็š„้ตใ€‚ ๆ–นๆณ•ไบŒ: ๆŽ’ๅบ ็”ฑๆ–ผไบ’็‚บๅญ—ๆฏ็•ฐไฝ่ฉž็š„ๅ…ฉๅ€‹ๅญ—ไธฒๅŒ…ๅซ็š„ๅญ—ๆฏ็›ธๅŒ๏ผŒๅ› ๆญคๅฐๅ…ฉๅ€‹ๅญ—ไธฒๅˆ†ๅˆฅ้€ฒ่กŒๆŽ’ๅบไน‹ๅพŒๅพ—ๅˆฐ็š„ๅญ—ไธฒไธ€ๅฎšๆ˜ฏ็›ธๅŒ็š„๏ผŒๆ•…ๅฏไปฅๅฐ‡ๆŽ’ๅบไน‹ๅพŒ็š„ๅญ—ไธฒไฝœ็‚บๅ“ˆๅธŒ่กจ็š„้ตใ€‚ ไพ†ๆบ https://leetcode.com/problems/group-anagrams/ https://leetcode.com/problems/group-anagrams/solutions/3645797/hash-solution-with-explanation-smart-solution-o-n-m/ https://leetcode.cn/problems/group-anagrams/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0049.Group-Anagams/main.go package groupanagrams import \"sort\" // ไฝฟ็”จ่จˆๆ•ธ: ๆ™‚้–“่ค‡้›œ O(nk), ็ฉบ้–“่ค‡้›œ O(nk) // n ๆ˜ฏๅ–ฎ่ฉž็š„ๅ€‹ๆ•ธ , kๆ˜ฏๅ–ฎๅญ—็š„ๆœ€ๅคง้•ทๅบฆ // O(n)้ๆญทๅ–ฎ่ฉž, ้ๆญทๅญ—็ฌฆO(nk) func GroupAnagrams(strs []string) [][]string { m := make(map[[26]int][]string, len(strs)) for _, str := range strs { // ๅปบ็ซ‹ๆฏไธ€ๅ€‹string็š„็‰นๅพต`count`, ่—‰็”ฑ็ตฑ่จˆๆฏๅ€‹ๅญ—ๆฏๅ‡บ็พ็š„ๆฌกๆ•ธ count := [26]int{} for _, b := range str { count[b-'a']++ } // ๅฐ‡ๅŒๆจฃ็š„ๆฌกๆ•ธ็š„stringๆ”พ็ฝฎๅœจ mapไธญ m[count] = append(m[count], str) } // ๆŠŠmapไธญ็š„stringๆ”พๅ…ฅๅˆฐ็ตๆžœ็š„ `[][]string` array ไธญ ans := [][]string{} for _, v := range m { ans = append(ans, v) } return ans } // ๆŽ’ๅบ: ๆ™‚้–“่ค‡้›œ O(nklog(k)), ็ฉบ้–“่ค‡้›œ O(klog(k)) // n ๆ˜ฏๅ–ฎ่ฉž็š„ๅ€‹ๆ•ธ , kๆ˜ฏๅ–ฎๅญ—็š„ๆœ€ๅคง้•ทๅบฆ // ้ๆญทๅ–ฎ่ฉž O(n) // ๆŽ’ๅบๅญ—็ฌฆ O(klog(k)) func GroupAnagramsBySort(strs []string) [][]string { m := make(map[string][]string, len(strs)) for _, str := range strs { // ๅปบ็ซ‹ๆฏไธ€ๅ€‹string็š„็‰นๅพต, ่—‰็”ฑ็ตฑ่จˆๆŽ’ๅบ s := []byte(str) sort.Slice(s, func(i, j int) bool { return s[i] Benchmark go test -benchmem -run=none LeetcodeGolang/Leetcode/0049.Group-Anagrams -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0049.Group-Anagrams cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkGroupAnagrams-8 899431 1615 ns/op 968 B/op 12 allocs/op BenchmarkGroupAnagramsBySort-8 592148 3566 ns/op 776 B/op 33 allocs/op PASS ok LeetcodeGolang/Leetcode/0049.Group-Anagrams 3.611s package groupanagrams import ( \"reflect\" \"sort\" \"testing\" ) var tests = []struct { arg1 []string want [][]string }{ { []string{\"eat\", \"tea\", \"tan\", \"ate\", \"nat\", \"bat\"}, [][]string{ {\"bat\"}, {\"nat\", \"tan\"}, {\"ate\", \"eat\", \"tea\"}}, }, { []string{}, [][]string{}, }, { []string{\"a\"}, [][]string{ {\"a\"}}, }, } // ๅ‰ตๅปบไธ€ๅ€‹่ผ”ๅŠฉๅ‡ฝๆ•ธ๏ผŒๅฐ‡ๅญ—็ฌฆไธฒๆ•ธ็ต„ๆŽ’ๅบ๏ผŒไปฅไพฟๆฏ”่ผƒ func sortSubStrings(groups [][]string) { for _, group := range groups { sort.Strings(group) } // ๆŽ’ๅบๆ•ดๅ€‹ๅˆ‡็‰‡ sort.Slice(groups, func(i, j int) bool { return groups[i][0] ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0053.Maximum-Subarray/":{"url":"Leetcode/0053.Maximum-Subarray/","title":"0053.Maximum Subarray","summary":"0053.Maximum-Subarray","keywords":"","body":"53. Maximum Subarray tagsstart LeetCode Go Medium Array Dynamic Programming Blind75 tagsstop ้กŒ็›ฎ Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle. ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆ•ดๆ•ธๆ•ธ็ต„ nums ๏ผŒๆ‰พๅˆฐไธ€ๅ€‹ๅ…ทๆœ‰ๆœ€ๅคงๅ’Œ็š„้€ฃ็บŒๅญๆ•ธ็ต„๏ผˆๅญๆ•ธ็ต„ๆœ€ๅฐ‘ๅŒ…ๅซไธ€ๅ€‹ๅ…ƒ็ด ๏ผ‰๏ผŒ่ฟ”ๅ›žๅ…ถๆœ€ๅคงๅ’Œใ€‚ ่งฃ้กŒๆ€่ทฏ ้€™ไธ€้กŒๅฏไปฅ็”จ DP ๆฑ‚่งฃไนŸๅฏไปฅไธ็”จ DPใ€‚ ้กŒ็›ฎ่ฆๆฑ‚่ผธๅ‡บๆ•ธ็ต„ไธญๆŸๅ€‹ๅ€้–“ๅ…งๆ•ธๅญ—ไน‹ๅ’Œๆœ€ๅคง็š„้‚ฃๅ€‹ๅ€ผใ€‚ dp[i] ่กจ็คบ[0,i] ๅ€้–“ๅ…งๅ„ๅ€‹ๅญๅ€้–“ๅ’Œ็š„ๆœ€ๅคงๅ€ผ๏ผŒ็‹€ๆ…‹่ฝ‰็งปๆ–น็จ‹ๆ˜ฏdp[i] = nums[i] + dp[i-1] (dp[i- 1] > 0)๏ผŒdp[i] = nums[i] (dp[i-1] โ‰ค 0)ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0053.Maximum-Subarray/ https://leetcode-cn.com/problems/maximum-subarray/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0053.Maximum-Subarray/Maximum-Subarray.go package maximumsubarray // MaxSubArrayDP : DP (dynamic programming) func MaxSubArrayDP(nums []int) int { if len(nums) == 0 { return 0 } if len(nums) == 1 { return nums[0] } dp, res := make([]int, len(nums)), nums[0] dp[0] = nums[0] for i := 1; i 0 { // ๅ‰ไธ€ๅ€‹ๅ’Œๆ˜ฏๆญฃ็š„ ็นผ็บŒๅŠ ไธ‹ๅŽป dp[i] = nums[i] + dp[i-1] } else { // ๅ‰ไธ€ๅ€‹ๅ’Œๆ˜ฏๅฐๆ–ผ็ญ‰ๆ–ผ0 ็›ดๆŽฅๆ‹ฟ็พๅœจๅ€ผๅ–ไปฃ dp[i] = nums[i] } res = max(res, dp[i]) } return res } // MaxSubArray1 : ๆจกๆ“ฌ, ๆฏ”DPๅฟซ func MaxSubArray1(nums []int) int { if len(nums) == 1 { return nums[0] } maxSum := 0 tmp := 0 for i := 0; i maxSum { maxSum = tmp } if tmp b { return a } return b } //TODO: ๅˆ†ๆฒปๆณ•\b, ้€™ๅ€‹ๅˆ†ๆฒปๆ–นๆณ•้กžไผผๆ–ผใ€Œ็ทšๆฎตๆจนๆฑ‚่งฃๆœ€้•ทๅ…ฌๅ…ฑไธŠๅ‡ๅญๅบๅˆ—ๅ•้กŒใ€็š„pushUpๆ“ไฝœ ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0059.Spiral-Matrix-II/":{"url":"Leetcode/0059.Spiral-Matrix-II/","title":"0059.Spiral Matrix II","summary":null,"keywords":"","body":"59. Spiral Matrix II tagsstart Medium Array tagsstop ้กŒ็›ฎ Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. Example: Input: 3 Output: [ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ] ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆญฃๆ•ดๆ•ธ n๏ผŒ็”Ÿๆˆไธ€ๅ€‹ๅŒ…ๅซ 1 ๅˆฐ n^2 ๆ‰€ๆœ‰ๅ…ƒ็ด ๏ผŒไธ”ๅ…ƒ็ด ๆŒ‰้ †ๆ™‚้‡้ †ๅบ่žบๆ—‹ๆŽ’ๅˆ—็š„ๆญฃๆ–นๅฝข็Ÿฉ้™ฃใ€‚ ่งฃ้กŒๆ€่ทฏ ็ตฆๅ‡บไธ€ๅ€‹ๆ•ธ็ต„ n๏ผŒ่ฆๆฑ‚่ผธๅ‡บไธ€ๅ€‹ n n ็š„ไบŒ็ถญๆ•ธ็ต„๏ผŒ่ฃก้ขๅ…ƒ็ด ๆ˜ฏ 1 - nn๏ผŒไธ”ๆ•ธ็ต„ๆŽ’ๅˆ—้ †ๅบๆ˜ฏ่žบๆ—‹ๆŽ’ๅˆ—็š„ ้€™ไธ€้กŒๆ˜ฏ็ฌฌ 54 ้กŒ็š„ๅŠ ๅผท็‰ˆ๏ผŒๆฒ’ๆœ‰้œ€่ฆๆณจๆ„็š„็‰นๆฎŠๆƒ…ๆณ๏ผŒ็›ดๆŽฅๆจกๆ“ฌๅณๅฏใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0059.Spiral-Matrix-II/ https://leetcode-cn.com/problems/spiral-matrix-ii/ ๆ•ธ็ต„๏ผš้€™ๅ€‹ๅพช็’ฐๅฏไปฅ่ฝ‰ๆ‡ตๅพˆๅคšไบบ๏ผ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0059.Spiral-Matrix-II/Spiral-Matrix-II.go package spiralmatrixii // GenerateMatrix : ๆŒ‰ๅฑคๆจกๆ“ฌ, ๆ™‚้–“่ค‡้›œ O(n^2) ็ฉบ้–“่ค‡้›œ O(1) func GenerateMatrix(n int) [][]int { result := make([][]int, n) for i := range result { result[i] = make([]int, n) } left, right, top, botton := 0, n-1, 0, n-1 num := 1 target := n * n for num = left; i-- { result[botton][i] = num num++ } botton-- // ๅทฆๅฑค botton to top, ๅทฆๅฑค้‚Š็•Œ++ for i := botton; i >= top; i-- { result[i][left] = num num++ } left++ } return result } // ๆจกๆ“ฌ : O(n) // https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0059.Spiral-Matrix-II/ func GenerateMatrix2(n int) [][]int { if n == 0 { return [][]int{} } if n == 1 { return [][]int{{1}} } result, visit, round, x, y, spDir := make([][]int, n), make([][]int, n), 0, 0, 0, [][]int{ {0, 1}, // ๆœๅณ {1, 0}, // ๆœไธ‹ {0, -1}, // ๆœๅทฆ {-1, 0}, // ๆœไธŠ } for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0070.Climbing-Stairs/":{"url":"Leetcode/0070.Climbing-Stairs/","title":"0070.Climbing Stairs","summary":"0070.Climbing-Stairs","keywords":"","body":"0070.Climbing Stairs tagsstart LeetCode Go Easy Climbing Stairs DP tagsstop ้กŒ็›ฎ You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Example 1: Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top. 1 step + 1 step 2 steps Example 2: Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top. 1 step + 1 step + 1 step 1 step + 2 steps 2 steps + 1 step Constraints: 1 Accepted: 2.8M Submissions: 5.4M Acceptance Rate: 52.3% ้กŒ็›ฎๅคงๆ„ ้กžไผผ Fibonacci Number ่งฃ้กŒๆ€่ทฏ ็ฐกๅ–ฎ็š„ DP๏ผŒ็ถ“ๅ…ธ็š„็ˆฌๆจ“ๆขฏๅ•้กŒ. ไธ€ๅ€‹ๆจ“ๆขฏๅฏไปฅ็”ฑ n-1 ๅ’Œ n-2 ็š„ๆจ“ๆขฏ็ˆฌไธŠไพ†ใ€‚ ้€™ไธ€้กŒๆฑ‚่งฃ็š„ๅ€ผๅฐฑๆ˜ฏๆ–ๆณข้‚ฃๅฅ‘ๆ•ธๅˆ—ใ€‚ Big O ๆ™‚้–“่ค‡้›œ : ็ฉบ้–“่ค‡้›œ : ไพ†ๆบ https://leetcode.com/problems/climbing-stairs/ https://leetcode.cn/problems/climbing-stairs/ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0070.Climbing-Stairs/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0070.Climbing-Stairs/main.go package climbingstairs // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(n) func ClimbStairs(n int) int { dp := make([]int, n+1) dp[0], dp[1] = 1, 1 for i := 2; i Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0070.Climbing-Stairs cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkClimbStairs-8 10386211 112.1 ns/op 320 B/op 1 allocs/op BenchmarkClimbStairsCache-8 10184984 118.8 ns/op 320 B/op 1 allocs/op BenchmarkClimbStairsRecursive-8 4 281980486 ns/op 320 B/op 1 allocs/op PASS ok LeetcodeGolang/Leetcode/0070.Climbing-Stairs 5.591s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0072.Edit-Distance/":{"url":"Leetcode/0072.Edit-Distance/","title":"0072. Edit Distance","summary":"","keywords":"","body":"0072. Edit Distance tagsstart Golang Hard Dynamic Programming Edit Distance tagsstop ้ข˜็›ฎ Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. You have the following three operations permitted on a word: Insert a character Delete a character Replace a character Example 1: Input: word1 = \"horse\", word2 = \"ros\" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e') Example 2: Input: word1 = \"intention\", word2 = \"execution\" Output: 5 Explanation: intention -> inention (remove 't') inention -> enention (replace 'i' with 'e') enention -> exention (replace 'n' with 'x') exention -> exection (replace 'n' with 'c') exection -> execution (insert 'u') Constraints: 0 word1 and word2 consist of lowercase English letters. ้กŒ็›ฎๅคงๆ„ ๅฏไปฅๅฐไธ€ๅ€‹ๅญ—็ฌฆไธฒ้€ฒ่กŒไธ‰็จฎๆ“ไฝœ, ๆ’ๅ…ฅ, ๅˆช้™ค, ๆ›ฟๆ› ็พๅœจ็ตฆไฝ ๅ…ฉๅ€‹ๅญ—็ฌฆไธฒword1,word2, ่จˆ็ฎ—ๅ‡บword1่ฝ‰ๆ›ๆˆword2ๆœ€ๅฐ‘้œ€่ฆๅคšๅฐ‘ๆฌกๆ“ไฝœ ่งฃ้กŒๆ€่ทฏ https://mp.weixin.qq.com/s/ShoZRjM8OyvDbZwoXh6ygg ่งฃๆฑบๅ…ฉๅ€‹ๅญ—็ฌฆไธฒ็š„ๅ‹•ๆ…‹่ฆๅŠƒๅ•้กŒ, ไธ€็ญ้ƒฝๆ˜ฏ็”จๅ…ฉๅ€‹ๆŒ‡้‡ i, j ๅˆ†ๅˆฅๆŒ‡ๅ‘ๅ…ฉๅ€‹ๅญ—็ฌฆไธฒ็š„ๆœ€ๅพŒ, ็„ถๅพŒไธ€ๆญฅๆญฅๅพ€ๅ‰่ตฐ, ็ธฎๅฐๅ•้กŒ็š„่ฆๆจก if word1[i] == word2[j]: skip i,jๅŒๆ™‚ๅพ€ๅ‰ else: # insert # delete # replace dp = [ [0,1,2,3,4,5], [1,1,2,2,3,4], [2,2,1,2,3,4], [3,3,2,2,2,3] ] word1 \\ word2 \"\" h o r s e \"\" 0 1 2 3 4 5 r 1 1 2 2 3 4 o 2 2 1 2 3 4 s 3 3 2 2 2 3 dp(i,j) ่ฟ”ๅ›žๅ€ผ, ๅฐฑๆ˜ฏ word1[0..i] ๅ’Œ word2[0..j]็š„ๆœ€ๅฐ็ทจ่ผฏ่ท้›ข dp(1,0) \"ro\" , \"h\" ๆœ€ๅฐ็ทจ่ผฏ่ท้›ข 2 dp[i-1][j-1] dp[i-1][j] dp[i][j-1] dp[i][j] ๆ›ฟๆ›/่ทณ้Ž ๅˆช้™ค ๆ’ๅ…ฅ ไพ†ๆบ https://leetcode.com/problems/edit-distance/ https://labuladong.gitee.io/algo/3/25/77/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0072.Edit-Distance/main.go package editdistance import \"fmt\" // ้ž่ฟด (ๆšดๅŠ›่งฃ) func MinDistance(word1 string, word2 string) int { var dp func(int, int) int dp = func(i, j int) int { // base case if i == -1 { return j + 1 } if j == -1 { return i + 1 } if word1[i] == word2[j] { // word1[0..i] ๅ’Œ word2[0..j]็š„ๆœ€ๅฐ็ทจ่ผฏ่ท้›ข็ญ‰ๆ–ผ word1[0..i-1] ๅ’Œ word2[0..j-1] // ๆœฌไพ†ๅฐฑ็›ธ็ญ‰ๆ‰€ไปฅไธ้œ€่ฆไปปไฝ•ๆ“ไฝœ // ไนŸๅฐฑๆ˜ฏ่ชช dp(i,j)็ญ‰ๆ–ผ dp(i-1,j-1) return dp(i-1, j-1) } else { return min( dp(i, j-1)+1, // insert: ็›ดๆŽฅๅœจ word1[i]ไธญๆ’ๅ…ฅไธ€ๅ€‹ๅ’Œword2[j]ไธ€ๆจฃ็š„ๅญ—็ฌฆ, ้‚ฃ้บผword2[j]ๅฐฑ่ขซๅŒน้…ไบ†,ๅพ€ๅ‰j, ็นผ็บŒๅ’Œiๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 dp(i-1, j)+1, // delete: ็›ดๆŽฅๆŠŠ word1[i] ้€™ๅ€‹ๅญ—็ฌฆไธฒๅˆช้™ค, ๅพ€ๅ‰ i ็นผ็บŒๅ’Œ j ๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 dp(i-1, j-1)+1, // replace: ็›ดๆŽฅๆŠŠ word1[i] ๆ›ฟๆ›ๆˆ word2[j], ้€™ๆจฃไป–ๅ€‘ๅฐฑๅŒน้…ไบ†, ๅŒๆ™‚ๅพ€ๅ‰ i, j ็นผ็บŒๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 ) } } return dp(len(word1)-1, len(word2)-1) } // Memoๅ„ชๅŒ– func MinDistanceMemo(word1 string, word2 string) int { var dp func(int, int) int memo := map[string]int{} dp = func(i, j int) int { key := fmt.Sprintf(\"%d,%d\", i, j) // ๆŸฅ่ฉขๅ‚™ๅฟ˜้Œ„ ้ฟๅ…้‡่ค‡ if _, ok := memo[key]; ok == true { return memo[key] } // base case if i == -1 { return j + 1 } if j == -1 { return i + 1 } if word1[i] == word2[j] { // word1[0..i] ๅ’Œ word2[0..j]็š„ๆœ€ๅฐ็ทจ่ผฏ่ท้›ข็ญ‰ๆ–ผ word1[0..i-1] ๅ’Œ word2[0..j-1] // ๆœฌไพ†ๅฐฑ็›ธ็ญ‰ๆ‰€ไปฅไธ้œ€่ฆไปปไฝ•ๆ“ไฝœ // ไนŸๅฐฑๆ˜ฏ่ชช dp(i,j)็ญ‰ๆ–ผ dp(i-1,j-1) memo[key] = dp(i-1, j-1) } else { memo[key] = min( dp(i, j-1)+1, // insert: ็›ดๆŽฅๅœจ word1[i]ไธญๆ’ๅ…ฅไธ€ๅ€‹ๅ’Œword2[j]ไธ€ๆจฃ็š„ๅญ—็ฌฆ, ้‚ฃ้บผword2[j]ๅฐฑ่ขซๅŒน้…ไบ†,ๅพ€ๅ‰j, ็นผ็บŒๅ’Œiๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 dp(i-1, j)+1, // delete: ็›ดๆŽฅๆŠŠ word1[i] ้€™ๅ€‹ๅญ—็ฌฆไธฒๅˆช้™ค, ๅพ€ๅ‰ i ็นผ็บŒๅ’Œ j ๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 dp(i-1, j-1)+1, // replace: ็›ดๆŽฅๆŠŠ word1[i] ๆ›ฟๆ›ๆˆ word2[j], ้€™ๆจฃไป–ๅ€‘ๅฐฑๅŒน้…ไบ†, ๅŒๆ™‚ๅพ€ๅ‰ i, j ็นผ็บŒๅฐๆฏ”, ๆ“ไฝœๆฌกๆ•ธ+1 ) } return memo[key] } return dp(len(word1)-1, len(word2)-1) } // DP table ๅ„ชๅŒ–, DP table ๆ˜ฏ่‡ชๅบ•ๅ‘ไธŠๆฑ‚่งฃ, ้ž่ฟดๆ˜ฏ่‡ช้ ‚ๅ‘ไธ‹ๆฑ‚่งฃ func MinDistanceDP(word1 string, word2 string) int { m, n := len(word1), len(word2) // ๅˆๅง‹ๅŒ– dp table : [][]int{} dp := make([][]int, m+1) for i := 0; i i { min = i } } return min } go test -benchmem -run=none LeetcodeGolang/Leetcode/0072.Edit-Distance -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0072.Edit-Distance cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkMinDistance-8 398260 3748 ns/op 0 B/op 0 allocs/op BenchmarkMinDistanceMemo-8 102272 10796 ns/op 2211 B/op 69 allocs/op BenchmarkMinDistanceDP-8 1944886 794.2 ns/op 688 B/op 9 allocs/op PASS ok LeetcodeGolang/Leetcode/0072.Edit-Distance 5.717s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0075.Sort-Colors/":{"url":"Leetcode/0075.Sort-Colors/","title":"0075.Sort Colors","summary":null,"keywords":"","body":"75. Sort Colors tagsstart Medium Sort tagsstop ้ข˜็›ฎ Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. Example 1: Input: [2,0,2,1,1,0] Output: [0,0,1,1,2,2] Follow up: A rather straight forward solution is a two-pass algorithm using counting sort.First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's. Could you come up with a one-pass algorithm using only constant space? ็ตฆๅฎšไธ€ๅ€‹ๅŒ…ๅซ็ด…่‰ฒใ€็™ฝ่‰ฒๅ’Œ่—่‰ฒ๏ผŒไธ€ๅ…ฑ n ๅ€‹ๅ…ƒ็ด ็š„ๆ•ธ็ต„๏ผŒๅŽŸๅœฐๅฐๅฎƒๅ€‘้€ฒ่กŒๆŽ’ๅบ๏ผŒไฝฟๅพ—็›ธๅŒ้ก่‰ฒ็š„ๅ…ƒ็ด ็›ธ้„ฐ๏ผŒไธฆๆŒ‰็…ง็ด…่‰ฒใ€็™ฝ่‰ฒใ€่—่‰ฒ้ †ๅบๆŽ’ๅˆ—ใ€‚ ๆญค้กŒไธญ๏ผŒๆˆ‘ๅ€‘ไฝฟ็”จๆ•ดๆ•ธ 0ใ€ 1 ๅ’Œ 2 ๅˆ†ๅˆฅ่กจ็คบ็ด…่‰ฒใ€็™ฝ่‰ฒๅ’Œ่—่‰ฒใ€‚ ็ฏ„ไพ‹ 1๏ผš ่ผธๅ…ฅ๏ผšnums = [2,0,2,1,1,0] ่ผธๅ‡บ๏ผš[0,0,1,1,2,2] ็ฏ„ไพ‹ 2๏ผš ่ผธๅ…ฅ๏ผšnums = [2,0,1] ่ผธๅ‡บ๏ผš[0,1,2] ็ฏ„ไพ‹ 3๏ผš ่ผธๅ…ฅ๏ผšnums = [0] ่ผธๅ‡บ๏ผš[0] ็ฏ„ไพ‹ 4๏ผš ่ผธๅ…ฅ๏ผšnums = [1] ่ผธๅ‡บ๏ผš[1] ๆ็คบ๏ผš n == nums.length 1 nums[i] ็‚บ 0ใ€1 ๆˆ– 2 ้€ฒ้šŽ๏ผš ไฝ ๅฏไปฅไธไฝฟ็”จไปฃ็ขผๅบซไธญ็š„ๆŽ’ๅบๅ‡ฝๆ•ธไพ†่งฃๆฑบ้€™้“้กŒๅ—Ž๏ผŸ ไฝ ่ƒฝๆƒณๅ‡บไธ€ๅ€‹ๅƒ…ไฝฟ็”จๅธธๆ•ธ็ฉบ้–“็š„ไธ€่ถŸๆŽƒๆ็ฎ—ๆณ•ๅ—Ž๏ผŸ ไพ†ๆบ๏ผšๅŠ›ๆ‰ฃ๏ผˆLeetCode๏ผ‰ ้ˆๆŽฅ๏ผšhttps://leetcode-cn.com/problems/sort-colors ่‘—ไฝœๆฌŠๆญธ้ ˜ๆ‰ฃ็ถฒ็ตกๆ‰€ๆœ‰ใ€‚ๅ•†ๆฅญ่ฝ‰่ผ‰่ซ‹่ฏ็นซๅฎ˜ๆ–นๆŽˆๆฌŠ๏ผŒ้žๅ•†ๆฅญ่ฝ‰่ผ‰่ซ‹่จปๆ˜Žๅ‡บ่™•ใ€‚ ้กŒ็›ฎๅคงๆ„ ๆŠฝ่ฑก้กŒๆ„ๅ…ถๅฏฆๅฐฑๆ˜ฏๆŽ’ๅบใ€‚้€™้กŒๅฏไปฅ็”จๅฟซๆŽ’ไธ€ๆฌก้€š้Žใ€‚ ่งฃ้กŒๆ€่ทฏ ้กŒ็›ฎๆœซๅฐพ็š„ Follow up ๆๅ‡บไบ†ไธ€ๅ€‹ๆ›ด้ซ˜็š„่ฆๆฑ‚๏ผŒ่ƒฝๅฆ็”จไธ€ๆฌกๅพช็’ฐ่งฃๆฑบๅ•้กŒ๏ผŸ้€™้กŒ็”ฑๆ–ผๆ•ธๅญ—ๅชๆœƒๅ‡บ็พ 0๏ผŒ1๏ผŒ2 ้€™ไธ‰ๅ€‹ๆ•ธๅญ—๏ผŒๆ‰€ไปฅ็”จๆธธๆจ™็งปๅ‹•ไพ†ๆŽงๅˆถ้ †ๅบไนŸๆ˜ฏๅฏไปฅ็š„ใ€‚ๅ…ท้ซ”ๅšๆณ•๏ผš0 ๆ˜ฏๆŽ’ๅœจๆœ€ๅ‰้ข็š„๏ผŒๆ‰€ไปฅๅช่ฆๆทปๅŠ ไธ€ๅ€‹ 0๏ผŒๅฐฑ้œ€่ฆๆ”พ็ฝฎ 1 ๅ’Œ 2ใ€‚1 ๆŽ’ๅœจ 2 ๅ‰้ข๏ผŒๆ‰€ไปฅๆทปๅŠ  1 ็š„ๆ™‚ๅ€™ไนŸ้œ€่ฆๆ”พ็ฝฎ 2 ใ€‚่‡ณๆ–ผๆœ€ๅพŒ็š„ 2๏ผŒๅช็”จ็งปๅ‹•ๆธธๆจ™ๅณๅฏใ€‚ ้€™้“้กŒๅฏไปฅ็”จ่จˆๆ•ธๆŽ’ๅบ๏ผŒ้ฉๅˆๅพ…ๆŽ’ๅบๆ•ธๅญ—ๅพˆๅฐ‘็š„้กŒ็›ฎใ€‚็”จไธ€ๅ€‹ 3 ๅ€‹ๅฎน้‡็š„ๆ•ธ็ต„ๅˆ†ๅˆฅ่จˆๆ•ธ๏ผŒ่จ˜้Œ„ 0๏ผŒ1๏ผŒ2 ๅ‡บ็พ็š„ๅ€‹ๆ•ธใ€‚็„ถๅพŒๅ†ๆ นๆ“šๅ€‹ๆ•ธๆŽ’ๅˆ— 0๏ผŒ1๏ผŒ2 ๅณๅฏใ€‚ๆ™‚้–“่ค‡้›œๅบฆ O(n)๏ผŒ็ฉบ้–“่ค‡้›œๅบฆ O(K)ใ€‚้€™ไธ€้กŒ K = 3ใ€‚ ้€™้“้กŒไนŸๅฏไปฅ็”จไธ€ๆฌกไธ‰่ทฏๅฟซๆŽ’ใ€‚ๆ•ธ็ต„ๅˆ†็‚บ 3 ้ƒจๅˆ†๏ผŒ็ฌฌไธ€ๅ€‹้ƒจๅˆ†้ƒฝๆ˜ฏ 0๏ผŒไธญ้–“้ƒจๅˆ†้ƒฝๆ˜ฏ 1๏ผŒๆœ€ๅพŒ้ƒจๅˆ†้ƒฝๆ˜ฏ 2 ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0075.Sort-Colors/ https://leetcode-cn.com/problems/sort-colors/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0075.Sort-Colors/0075.Sort-Colors.go package sortcolors func sortColors(nums []int) { if len(nums) == 0 { return } var index0, index1, index2 = 0, 0, 0 for _, num := range nums { switch num { case 0: nums[index2] = 2 index2++ nums[index1] = 1 index1++ nums[index0] = 0 index0++ case 1: nums[index2] = 2 index2++ nums[index1] = 1 index1++ case 2: index2++ } } } /* ไบŒ่ทฏๅฟซๆŽ’่ˆ‡ไธ‰่ทฏๅฟซๆŽ’ ๅ…ˆๆŽŒๆกไบŒ่ทฏๅฟซๆŽ’๏ผŒ https://leetcode-cn.com/problems/sort-an-array/solution/golang-er-lu-kuai-pai-by-rqb-2/ ไธ‰่ทฏๅฟซๆŽ’็จๅพฎๆ”นไธ‹ๅณๅฏ ๅ€ๅˆฅ๏ผš ไบŒ่ทฏๅฟซๆŽ’๏ผŒๅˆ†ๅ…ฉ้ƒจๅˆ†๏ผšๅฐๆ–ผ็ญ‰ๆ–ผใ€ๅคงๆ–ผไบŒ้ƒจๅˆ†ใ€‚ ไธ‰่ทฏๅฟซๆŽ’ๅˆ†็‚บ๏ผŒๅฐๆ–ผใ€็ญ‰ๆ–ผใ€ๅคงๆ–ผไธ‰้ƒจๅˆ†ใ€‚ ไธ‰่ทฏๅฟซๆŽ’๏ผš ็›ธๆฏ”ไบŒ่ทฏๅฟซๆŽ’ๅขžๅŠ ไธ€ๅ€‹่ฎŠ้‡่จ˜้Œ„็›ธ็ญ‰็š„่ตทๅง‹ๅ…ƒ็ด ใ€‚ ๅ‡่จญ้ธๆ“‡ๆ•ธ็ต„็ฌฌไธ€ๅ€‹ๅ…ƒ็ด ไฝœ็‚บๅƒ่€ƒๅ…ƒ็ด ใ€‚ๅ‰‡่ตทๅง‹ไธ‹้‚Š็‚บ0๏ผŒๅณ็‚บequalHead ไฝœ่€…๏ผšhibrq ้“พๆŽฅ๏ผšhttps://leetcode-cn.com/problems/sort-an-array/solution/golang-san-lu-kuai-pai-by-rqb-2/ ๆฅๆบ๏ผšๅŠ›ๆ‰ฃ๏ผˆLeetCode๏ผ‰ ่‘—ไฝœๆƒๅฝ’ไฝœ่€…ๆ‰€ๆœ‰ใ€‚ๅ•†ไธš่ฝฌ่ฝฝ่ฏท่”็ณปไฝœ่€…่Žทๅพ—ๆŽˆๆƒ๏ผŒ้žๅ•†ไธš่ฝฌ่ฝฝ่ฏทๆณจๆ˜Žๅ‡บๅค„ใ€‚ */ func sortColorsQuickSort(nums []int) { if len(nums) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0078.Subsets/":{"url":"Leetcode/0078.Subsets/","title":"0078. Subsets","summary":"0078.Subsets","keywords":"","body":"0078. Subsets tagsstart LeetCode Go Medium Subsets tagsstop ้กŒ็›ฎ Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order. Example 1: Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] Example 2: Input: nums = [0] Output: [[],[0]] Constraints: 1 ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€็ต„ไธๅซ้‡่ค‡ๅ…ƒ็ด ็š„ๆ•ดๆ•ธ้™ฃๅˆ— nums๏ผŒ่ฟ”ๅ›ž่ฉฒ้™ฃๅˆ—ๆ‰€ๆœ‰ๅฏ่ƒฝ็š„ๅญ้›†๏ผˆๅ†ช้›†๏ผ‰ใ€‚ ่ชชๆ˜Ž๏ผš่งฃ้›†ไธ่ƒฝๅŒ…ๅซ้‡่ค‡็š„ๅญ้›†ใ€‚ ่งฃ้กŒๆ€่ทฏ ๆ‰พๅ‡บไธ€ๅ€‹้›†ๅˆไธญ็š„ๆ‰€ๆœ‰ๅญ้›†๏ผŒ็ฉบ้›†ไนŸ็ฎ—ๆ˜ฏๅญ้›†ใ€‚ ไธ”้™ฃๅˆ—ไธญ็š„ๆ•ธไฝไธๆœƒๅ‡บ็พ้‡่ค‡ใ€‚ ็”จ DFS ๆšดๅŠ›ๆžš่ˆ‰ๅณๅฏใ€‚ ้€™ไธ€้กŒๅ’Œ็ฌฌ 90 ้กŒ๏ผŒ็ฌฌ 491 ้กŒ้กžไผผ๏ผŒๅฏไปฅไธ€่ตท่งฃ็ญ”ๅ’Œ่ค‡็ฟ’ Big O ๆ™‚้–“่ค‡้›œ : O(n^2) ็ฉบ้–“่ค‡้›œ : O(n) ไพ†ๆบ https://leetcode.com/problems/subsets/description/ https://leetcode.cn/problems/subsets/description/ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0078.Subsets/ https://github.com/suntong/lang/blob/master/lang/Go/src/ds/Recursion/LC-0B-Subsets-2.go ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0078.Subsets/main.go package subsets // ๆ™‚้–“่ค‡้›œ O(n^2) , ็ฉบ้–“่ค‡้›œ O(n) func Subsets(nums []int) [][]int { path, result := []int{}, [][]int{} for i := 0; i Benchmark go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. -cover goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkMaxEnvelopes-8 7799131 160.3 ns/op 88 B/op 3 allocs/op BenchmarkMaxEnvelopes2-8 5800399 195.6 ns/op 80 B/op 4 allocs/op PASS coverage: 96.0% of statements ok LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes 3.726s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0088.Merge-Sorted-Array/":{"url":"Leetcode/0088.Merge-Sorted-Array/","title":"0088.Merge Sorted Array","summary":null,"keywords":"","body":"88. Merge Sorted Array tagsstart Easy Array tagsstop ้กŒ็›ฎ Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array. Note: You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively. Example: Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6] Constraints: -10^9 ้กŒ็›ฎๅคงๆ„ ๅˆไฝตๅ…ฉๅ€‹ๅทฒ็ถ“ๆœ‰ๅบ็š„ๆ•ธ็ต„๏ผŒ็ตๆžœๆ”พๅœจ็ฌฌไธ€ๅ€‹ๆ•ธ็ต„ไธญ๏ผŒ็ฌฌไธ€ๅ€‹ๆ•ธ็ต„ๅ‡่จญ็ฉบ้–“่ถณๅค ๅคงใ€‚่ฆๆฑ‚็ฎ—ๆณ•ๆ™‚้–“่ค‡้›œๅบฆ่ถณๅค ไฝŽใ€‚ ่งฃ้กŒๆ€่ทฏ ็‚บไบ†ไธๅคง้‡็งปๅ‹•ๅ…ƒ็ด ๏ผŒๅฐฑ่ฆๅพž2ๅ€‹ๆ•ธ็ต„้•ทๅบฆไน‹ๅ’Œ็š„ๆœ€ๅพŒไธ€ๅ€‹ไฝ็ฝฎ้–‹ๅง‹๏ผŒไพๆฌก้ธๅ–ๅ…ฉๅ€‹ๆ•ธ็ต„ไธญๅคง็š„ๆ•ธ๏ผŒๅพž็ฌฌไธ€ๅ€‹ๆ•ธ็ต„็š„ๅฐพๅทด้–‹ๅง‹ๅพ€้ ญๆ”พ๏ผŒๅช่ฆๅพช็’ฐไธ€ๆฌกไปฅๅพŒ๏ผŒๅฐฑ็”Ÿๆˆไบ†ๅˆไฝตไปฅๅพŒ็š„ๆ•ธ็ต„ไบ†ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0088.Merge-Sorted-Array/ https://leetcode-cn.com/problems/merge-sorted-array/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0088.Merge-Sorted-Array/Merge-Sorted-Array.go package mergesortedarray func Merge(nums1 []int, m int, nums2 []int, n int) { if m == 0 { copy(nums1, nums2) return } num1Idx, num2Idx, tail := m-1, n-1, m+n-1 // ๅพžๆฏไธ€ๅ€‹array็š„ๅพŒ้ข้–‹ๅง‹ๆฏ”่ผƒ, ไธฆๆ”พๅ…ฅๆœ€ๅพŒ้ข็š„ไฝๅญ. ้€™ๆจฃๅช่ฆ่ท‘ไธ€ๆฌก for ; num1Idx >= 0 && num2Idx >= 0; tail-- { if nums1[num1Idx] > nums2[num2Idx] { nums1[tail] = nums1[num1Idx] num1Idx-- } else { nums1[tail] = nums2[num2Idx] num2Idx-- } } // ๅฐ‡ๅฐšๆœช่ท‘ๅฎŒ็š„่ฃœ้ฝŠ for ; num2Idx > 0; tail-- { nums1[tail] = nums2[num2Idx] num2Idx-- } } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0094.Binary-Tree-Inorder-Traversal/":{"url":"Leetcode/0094.Binary-Tree-Inorder-Traversal/","title":"0094.Binary Tree Inorder Traversal","summary":null,"keywords":"","body":"94. Binary Tree Inorder Traversal tagsstart Medium Stack tagsstop ้กŒ็›ฎ Given a binary tree, return the inorder traversal of its nodes' values. Example : Input: [1,null,2,3] 1 \\ 2 / 3 Output: [1,3,2] Follow up: Recursive solution is trivial, could you do it iteratively? ้กŒ็›ฎๅคงๆ„ ไธญๅบ้ๆญทไธ€้ก†ๆจน ่งฃ้กŒๆ€่ทฏ ๆทฑๅบฆๅ„ชๅ…ˆ ไธญๅบ้ๆญท ่‹ฅไบŒๅ…ƒๆจน็‚บ็ฉบๅ›žๅ‚ณ็ฉบ, ๅฆๅ‰‡ๅพžๆ น็ต้ปž้–‹ๅง‹, ๅ…ˆ่ตฐ่จชๆ น็ฏ€้ปž็š„ๅทฆๅญๆจน -> ๆ น็ฏ€้ปž -> ๅณๅญๆจน ๆทฑๅบฆๅ„ชๅ…ˆ, ๅ‰ๅบ้ๆญท ่‹ฅไบŒๅ…ƒๆจน็‚บ็ฉบๅ›žๅ‚ณ็ฉบ, ๅฆๅ‰‡ๅ…ˆๆ น็ฏ€้ปž-> ๅทฆๅญๆจน -> ๅณๅญๆจน ๆทฑๅบฆๅ„ชๅ…ˆ, ๅพŒๅบ้ๆญท ่‹ฅไบŒๅ…ƒๆจน็‚บ็ฉบๅ›žๅ‚ณ็ฉบ, ๅฆๅ‰‡ๅพžๅทฆๅˆฐๅณ่ช’ไธฆๅพž่‘‰ๅญ็ฏ€้ปžๅพŒ็บŒ่ตฐ่จชๅทฆๅญๆจนๅˆฐๅณๅญๆจน, ๆœ€ๅพŒๆ˜ฏๆ‹œ่จชๆ น็ฏ€้ปž ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0094.Binary-Tree-Inorder-Traversal/ https://leetcode-cn.com/problems/binary-tree-inorder-traversal/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0094.Binary-Tree-Inorder-Traversal/Binary-Tree-Inorder-Traversal.go package binarytreeinordertraversal import ( \"LeetcodeGolang/Utility/structures\" ) type TreeNode = structures.TreeNode func InorderTraversalStack(root *TreeNode) []int { var result []int inorderStack(root, &result) return result } func InorderTraversalRecursion(root *TreeNode) []int { var result []int inorderRecursion(root, &result) return result } func inorderRecursion(root *TreeNode, r *[]int) { if root != nil { inorderRecursion(root.Left, r) *r = append(*r, root.Val) inorderRecursion(root.Right, r) } } func inorderStack(root *TreeNode, r *[]int) { s := structures.NewArrayStack() p := root for !s.IsEmpty() || p != nil { if p != nil { // ๆŠŠไธญ้–“ๆ”พๅ…ฅstack, ๅพ€ๅทฆ็ฏ€้ปž็นผ็บŒๅพ€ไธ‹ๆ‰พ s.Push(p) p = p.Left } else { // ๆ‰พไธๅˆฐๆ™‚,ๅฐๅ‡บ tmp := s.Pop().(*TreeNode) *r = append(*r, tmp.Val) p = tmp.Right } } } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0100.Same-Tree/":{"url":"Leetcode/0100.Same-Tree/","title":"100. Same Tree","summary":"0100.Same-Tree","keywords":"","body":"100. Same Tree tagsstart LeetCode Go Easy Same Tree Tree tagsstop ้กŒ็›ฎ Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value. Example 1: Input: p = [1,2,3], q = [1,2,3] Output: true Example 2: Input: p = [1,2], q = [1,null,2] Output: false Example 3: Input: p = [1,2,1], q = [1,1,2] Output: false Constraints: The number of nodes in both trees is in the range [0, 100]. -104 Accepted: 1.8M Submissions: 3.1M Acceptance Rate: 60.3% ้กŒ็›ฎๅคงๆ„ ๅˆคๆ–ท 2 ้ก†ๆจนๆ˜ฏๅฆๆ˜ฏๅฎŒๅ…จ็›ธ็ญ‰็š„ ่งฃ้กŒๆ€่ทฏ ้žๆญธๅˆคๆ–ทๅณๅฏ Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : O(1) ไพ†ๆบ https://leetcode.com/problems/same-tree/ https://leetcode.cn/problems/same-tree/ https://books.halfrost.com/leetcode/ChapterFour/0100~0199/0100.Same-Tree/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0100.Same-Tree/main.go package sametree import \"LeetcodeGolang/structures\" /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type TreeNode = structures.TreeNode // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) func IsSameTree(p *TreeNode, q *TreeNode) bool { if p == nil && q == nil { return true } else if p != nil && q != nil { if p.Val == q.Val { return IsSameTree(p.Left, q.Left) && IsSameTree(p.Right, q.Right) } return false } else { return false } } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0104.Maximum-Depth-of-Binary-Tree/":{"url":"Leetcode/0104.Maximum-Depth-of-Binary-Tree/","title":"0104.Maximum Depth of Binary Tree","summary":"0104.Maximum-Depth-of-Binary-Tree","keywords":"","body":"0104.Maximum Depth of Binary Tree tagsstart LeetCode Go Easy LEETCODETITLE tagsstop ้กŒ็›ฎ Given the root of a binary tree, return its maximum depth. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example 1: Input: root = [3,9,20,null,null,15,7] Output: 3 Example 2: Input: root = [1,null,2] Output: 2 Constraints: The number of nodes in the tree is in the range [0, 104]. -100 Accepted 2.7M Submissions 3.6M Acceptance Rate 74.7% ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : ็ฉบ้–“่ค‡้›œ : ไพ†ๆบ https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0104.Maximum-Depth-of-Binary-Tree/main.go Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/":{"url":"Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/","title":"105. Construct Binary Tree from Preorder and Inorder Traversal","summary":"0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal","keywords":"","body":"105. Construct Binary Tree from Preorder and Inorder Traversal tagsstart LeetCode Go Medium Construct Binary Tree from Preorder and Inorder Traversal Array Hash Table Divide and Conquer Tree Binary Tree tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : O(n) nๅ€‹ๆจน็ฏ€้ปž ็ฉบ้–“่ค‡้›œ : O(n) ้ž่ฟด่ชฟ็”จ็š„Stack็ฉบ้–“ๆ˜ฏ O(h)๏ผŒๅ…ถไธญ h ๆ˜ฏๆจน็š„้ซ˜ๅบฆใ€‚ ๅœจๆฏๅ€‹้ž่ฟดๅฑค็ดšไธญ๏ผŒ้ƒฝๅ‰ตๅปบไบ†ไธ€ๅ€‹ TreeNode ๅฐ่ฑก๏ผŒๅ› ๆญค็ฉบ้–“่ค‡้›œๅบฆไนŸๆ˜ฏ O(n)๏ผŒๅ…ถไธญ n ๆ˜ฏ็ฏ€้ปž็š„ๆ•ธ้‡ใ€‚ h ไพ†ๆบ https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ https://leetcode.cn/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/main.go /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() func buildTree(preorder []int, inorder []int) *TreeNode { if len(preorder) == 0 { return nil } result := &TreeNode{preorder[0], nil, nil} i := 0 for ; i Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0110.Balanced-Binary-Tree/":{"url":"Leetcode/0110.Balanced-Binary-Tree/","title":"110. Balanced Binary Tree","summary":"0110.Balanced-Binary-Tree","keywords":"","body":"110. Balanced Binary Tree tagsstart LeetCode Go Easy Balanced Binary Tree DFS tagsstop ้กŒ็›ฎ Given a binary tree, determine if it is height-balanced . Example 1: Input: root = [3,9,20,null,null,15,7] Output: true Example 2: Input: root = [1,2,2,3,3,null,null,4,4] Output: false Example 3: Input: root = [] Output: true Constraints: The number of nodes in the tree is in the range [0, 5000]. -104 ้กŒ็›ฎๅคงๆ„ ๅˆคๆ–ทไธ€ๆฃตๆจนๆ˜ฏไธๆ˜ฏๅนณ่กกไบŒๅ‰ๆจนใ€‚ ๅนณ่กกไบŒๅ‰ๆจน็š„ๅฎš็พฉๆ˜ฏ๏ผšๆจนไธญๆฏๅ€‹็ฏ€้ปž้ƒฝๆปฟ่ถณๅทฆๅณๅ…ฉๅ€‹ๅญๆจน็š„้ซ˜ๅบฆๅทฎ ่งฃ้กŒๆ€่ทฏ ้ซ˜ๅบฆ้‹็ฎ—ๅฏไฝฟ็”จ 0104.Maximum-Depth-of-Binary-Tree ๅนณ่กกไบŒๅ‰ๆจน๏ผˆBalanced Binary Tree๏ผ‰ๆ˜ฏไธ€็จฎไบŒๅ‰ๆจน๏ผŒๅ…ถๅทฆๅณๅญๆจน็š„้ซ˜ๅบฆๅทฎไธ่ถ…้Žไธ€็š„ไบŒๅ‰ๆจนใ€‚ๆ›ๅฅ่ฉฑ่ชช๏ผŒๅฐๆ–ผๆจนไธญ็š„ๆฏๅ€‹็ฏ€้ปž๏ผŒๅ…ถๅทฆๅญๆจนๅ’Œๅณๅญๆจน็š„้ซ˜ๅบฆๅทฎไธๅพ—ๅคงๆ–ผ1ใ€‚ ๅนณ่กกไบŒๅ‰ๆจน็š„ไธป่ฆ็›ฎ็š„ๆ˜ฏ็ขบไฟๆจน็š„้ซ˜ๅบฆๅนณ่กก๏ผŒ้€™ๆœ‰ๅŠฉๆ–ผไฟๆŒๅœจๆœ€ๅฃžๆƒ…ๆณไธ‹็š„ๆŸฅๆ‰พใ€ๆ’ๅ…ฅๅ’Œๅˆช้™คๆ“ไฝœ็š„ๆ™‚้–“่ค‡้›œๅบฆๅœจO(log n)็ฏ„ๅœๅ…ง๏ผŒๅ…ถไธญnๆ˜ฏๆจนไธญ็ฏ€้ปž็š„ๆ•ธ้‡ใ€‚้€™็จฎๅนณ่กกๆ€งๆœ‰ๅŠฉๆ–ผ็ขบไฟๆจน็š„ๆ€ง่ƒฝ่‰ฏๅฅฝ๏ผŒไธฆๆธ›ๅฐ‘ๆ“ไฝœ็š„ๅนณๅ‡ๆ™‚้–“่ค‡้›œๅบฆใ€‚ Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : O(1) ไพ†ๆบ https://leetcode.com/problems/balanced-binary-tree/ https://leetcode.cn/problems/balanced-binary-tree/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0110.Balanced-Binary-Tree/main.go package balancedbinarytree import \"LeetcodeGolang/structures\" // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type TreeNode = structures.TreeNode func IsBalanced(root *TreeNode) bool { if root == nil { return true } leftHight := depth(root.Left) rightHight := depth(root.Right) return abs(leftHight-rightHight) b { return a } return b } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/":{"url":"Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/","title":"0121.Best Time to Buy and Sell Stock","summary":"0121.Best-Time-to-Buy-and-Sell-Stock","keywords":"","body":"0121.Best Time to Buy and Sell Stock) tagsstart LeetCode Go Easy Slide Windows DP Best Time to Buy and Sell Stock array Blind75 tagsstop ้กŒ็›ฎ You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. Example 1: Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell. Example 2: Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the max profit = 0. Constraints: 1 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : O(1) ไพ†ๆบ https://leetcode.com/problems/valid-parentheses/ https://leetcode.cn/problems/valid-parentheses/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/main.go package besttimetobuyandsellstock type numbers interface { int | int8 | int16 | int32 | int64 | float32 | float64 } func max[T numbers](a T, b T) T { if a > b { return a } return b } // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) // Slide windows func MaxProfit(prices []int) int { left, right := 0, 1 maxProfit := 0 for right maxProfit { maxProfit = profit } } } return maxProfit } // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() // DP func MaxProfitDP2(prices []int) int { n := len(prices) dp := make([][]int, n) for i := 0; i Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkMaxProfit-8 208734571 8.156 ns/op 0 B/op 0 allocs/op BenchmarkMaxProfitDP-8 240880467 5.720 ns/op 0 B/op 0 allocs/op BenchmarkMaxProfitDP2-8 4095866 282.6 ns/op 240 B/op 7 allocs/op PASS ok LeetcodeGolang/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock 6.732s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0125.Valid-Palindrome/":{"url":"Leetcode/0125.Valid-Palindrome/","title":"0125. Valid Palindrome","summary":"Valid Palindrome","keywords":"","body":"0125. Valid Palindrome tagsstart LeetCode Go Easy Valid Palindrome tagsstop ้กŒ็›ฎ 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 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ๅทฆๅณๆŒ‡้‡ Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : O(1) ไพ†ๆบ https://leetcode.com/problems/valid-palindrome https://leetcode.cn/problems/valid-palindrome ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0125.Valid-Palindrome/main.go package validpalindrome import ( \"strings\" \"unicode\" ) // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() func IsPalindrome(s string) bool { // ๅฐ‡ๅญ—็ฌฆ่ฝ‰ๆˆๅฐๅฏซ, s = strings.ToLower(s) // ไฝฟ็”จ้›™ๆŒ‡้‡, ไธ€ๅทฆไธ€ๅณ็›ธๅ‘่€Œ่กŒ, ๅˆคๆ–ทๅ›žๆ–‡ left, right := 0, len(s)-1 for left Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0125.Valid-Palindrome cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkIsPalindrome-8 3840048 552.2 ns/op 32 B/op 1 allocs/op BenchmarkIsPalindromeStrBuilder-8 3164848 439.0 ns/op 88 B/op 4 allocs/op PASS ok LeetcodeGolang/Leetcode/0125.Valid-Palindrome 5.242s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0128.Longest-Consecutive-Sequence/":{"url":"Leetcode/0128.Longest-Consecutive-Sequence/","title":"128. Longest Consecutive Sequence","summary":"0128.Longest-Consecutive-Sequence","keywords":"","body":"128. Longest Consecutive Sequence tagsstart LeetCode Go Medium Longest Consecutive Sequence Array Hash Table Union Find Amazon Microsoft Google Adobe Spotify tagsstop ้กŒ็›ฎ ็ตฆๅฎšไธ€ๅ€‹ๆœชๆŽ’ๅบ็š„ๆ•ดๆ•ธๆ•ธไฝๅˆ— nums ๏ผŒๆ‰พๅ‡บๆ•ธๅญ—้€ฃ็บŒ็š„ๆœ€้•ทๅบๅˆ—๏ผˆไธ่ฆๆฑ‚ๅบๅˆ—ๅ…ƒ็ด ๅœจๅŽŸ้™ฃๅˆ—ไธญ้€ฃ็บŒ๏ผ‰็š„้•ทๅบฆใ€‚ ่ซ‹ไฝ ่จญ่จˆไธฆๅฏฆ็พๆ™‚้–“่ค‡้›œๅบฆ็‚บ O(n) ็š„ๆผ”ๆผ”็ฎ—ๆณ•่งฃๆฑบๆญคๅ•้กŒใ€‚ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : O(n) ไพ†ๆบ https://leetcode.com/problems/longest-consecutive-sequence/description/ https://leetcode.cn/problems/longest-consecutive-sequence/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0128.Longest-Consecutive-Sequence/main.go package longestconsecutivesequence // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() func longestConsecutive(nums []int) int { m := make(map[int]struct{}, len(nums)) for _, num := range nums { m[num] = struct{}{} } result := 0 for v := range m { // ๅฆ‚ๆžœๆฒ’ๆ‰พๅˆฐ่ฉฒๆ•ธๅญ—็š„ๅ‰ไธ€ๅ€‹ๆ•ธๅญ—, ๅ‰‡ๆŠŠ่ฉฒๆ•ธๅญ—ๅˆ€ๅš้€ฃ็บŒๅบๅˆ—็š„็ฌฌไธ€ๅ€‹ๆ•ธ if _, ok := m[v-1]; !ok { length := 1 for _, exit := m[v+length]; exit; _, exit = m[v+length] { length++ } if result Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0138.Copy-List-with-Random-Pointer/":{"url":"Leetcode/0138.Copy-List-with-Random-Pointer/","title":"138. Copy List with Random Pointer","summary":"0138.Copy-List-with-Random-Pointer","keywords":"","body":"138. Copy List with Random Pointer tagsstart LeetCode Go Medium Copy List with Random Pointer Facebook Amazon Microsoft Bloomberg Google tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ๅฐๆ–ผๆ•ธๆ“š็ตๆง‹่ค‡่ฃฝ๏ผŒ็”ญ็ฎกไป–ๆ€Ž้บผ่ฎŠ๏ผŒไฝ ๅฐฑ่จ˜ไฝๆœ€็ฐกๅ–ฎ็š„ๆ–นๅผ๏ผšไธ€ๅ€‹ๅ“ˆๅธŒ่กจ + ๅ…ฉๆฌก้ๆญท ็ฌฌไธ€ๆฌก้ๆญทๅฐˆ้–€clone็ฏ€้ปž๏ผŒ่—‰ๅŠฉ Hash่กจๆŠŠๅŽŸๅง‹็ฏ€้ปžๅ’Œclone็ฏ€้ปž็š„ๆ˜ ๅฐ„ๅญ˜ๅ„ฒ่ตทไพ†; ็ฌฌไบŒๆฌกๅฐˆ้–€็ต„่ฃ็ฏ€้ปž๏ผŒ็…ง่‘—ๅŽŸๆ•ธๆ“š็ตๆง‹็š„ๆจฃๅญ๏ผŒๆŠŠclone็ฏ€้ปž็š„ๆŒ‡ๆจ™็ต„่ฃ่ตทไพ†ใ€‚ Big O ๆ™‚้–“่ค‡้›œ : O(n) ๏ผŒๅ…ถไธญ n ๆ˜ฏ้ˆ่กจ็š„้•ทๅบฆใ€‚ ๅฐๆ–ผๆฏๅ€‹็ฏ€้ปž๏ผŒๆˆ‘ๅ€‘่‡ณๅคš่จชๅ•ๅ…ถใ€ŒๅพŒ็นผ็ฏ€้ปžใ€ๅ’Œใ€Œ้šจๆฉŸๆŒ‡ๆจ™ๆŒ‡ๅ‘็š„็ฏ€้ปžใ€ๅ„ไธ€ๆฌก๏ผŒๅ‡ๆ”คๆฏๅ€‹้ปž่‡ณๅคš่ขซ่จชๅ•ๅ…ฉๆฌกใ€‚ ็ฉบ้–“่ค‡้›œ : O(n) ๅ…ถไธญ n ๆ˜ฏ้ˆ่กจ็š„้•ทๅบฆใ€‚ ็‚บๅ“ˆๅธŒ่กจ็š„็ฉบ้–“้–‹้Šท ไพ†ๆบ https://leetcode.com/problems/copy-list-with-random-pointer/description/ https://leetcode.cn/problems/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0138.Copy-List-with-Random-Pointer/main.go package copylistwithrandompointer /** * Definition for a Node. * type Node struct { * Val int * Next *Node * Random *Node * } */ var cacheMap map[*Node]*Node // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(n) func copyRandomList(head *Node) *Node { cacheMap = make(map[*Node]*Node) return deepCopy(head) } func deepCopy(node *Node) *Node { if node == nil { return nil } if n, ok := cacheMap[node]; ok { return n } newNode := &Node{Val: node.Val} cacheMap[node] = newNode newNode.Next = deepCopy(node.Next) newNode.Random = deepCopy(node.Random) return newNode } func copyRandomList2(head *Node) *Node { cMap := make(map[*Node]*Node) cur := head // ็ฌฌไธ€ๆฌก้ๆญทๅฐˆ้–€clone็ฏ€้ปž๏ผŒ่—‰ๅŠฉ Hash่กจๆŠŠๅŽŸๅง‹็ฏ€้ปžๅ’Œclone็ฏ€้ปž็š„ๆ˜ ๅฐ„ๅญ˜ๅ„ฒ่ตทไพ†; for cur != nil { newNode := &Node{Val: cur.Val} cMap[cur] = newNode cur = cur.Next } // ็ฌฌไบŒๆฌกๅฐˆ้–€็ต„่ฃ็ฏ€้ปž๏ผŒ็…ง่‘—ๅŽŸๆ•ธๆ“š็ตๆง‹็š„ๆจฃๅญ๏ผŒๆŠŠclone็ฏ€้ปž็š„ๆŒ‡ๆจ™็ต„่ฃ่ตทไพ†ใ€‚ newHead := cMap[head] for head != nil { node := cMap[head] node.Next = cMap[head.Next] node.Random = cMap[head.Random] head = head.Next } return newHead } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0141.Linked-List-Cycle/":{"url":"Leetcode/0141.Linked-List-Cycle/","title":"0141.Linked List Cycle","summary":null,"keywords":"","body":"141. Linked List Cycle tagsstart Easy Linked List Two Pointers tagsstop ้กŒ็›ฎ Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? ้กŒ็›ฎๅคงๆ„ ๅˆคๆ–ท้Š่กจๆ˜ฏๅฆๆœ‰็’ฐ๏ผŒไธ่ƒฝไฝฟ็”จ้กๅค–็š„็ฉบ้–“ใ€‚ ่งฃ้กŒๆ€่ทฏ ็ตฆ 2 ๅ€‹ๆŒ‡้‡๏ผŒไธ€ๅ€‹ๆŒ‡้‡ๆ˜ฏๅฆๅค–ไธ€ๅ€‹ๆŒ‡้‡็š„ไธ‹ไธ€ๅ€‹ๆŒ‡้‡ใ€‚ๅฟซๆŒ‡้‡ไธ€ๆฌก่ตฐ 2 ๆ ผ๏ผŒๆ…ขๆŒ‡้‡ไธ€ๆฌก่ตฐ 1 ๆ ผใ€‚ๅฆ‚ๆžœๅญ˜ๅœจ็’ฐ๏ผŒ้‚ฃ้บผๅ‰ไธ€ๅ€‹ๆŒ‡้‡ไธ€ๅฎšๆœƒ็ถ“้Ž่‹ฅๅนฒๅœˆไน‹ๅพŒ่ฟฝไธŠๆ…ข็š„ๆŒ‡้‡ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0100~0199/0141.Linked-List-Cycle/ https://leetcode-cn.com/problems/linked-list-cycle/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0141.Linked-List-Cycle/Linked-List-Cycle.go package linkedlistcycle type ListNode struct { Val int Next *ListNode } func HasCycle(head *ListNode) bool { fast := head slow := head for slow != nil && fast != nil && fast.Next != nil { fast = fast.Next.Next slow = slow.Next if slow == fast { return true } } return false } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0142.Linked-List-CycleII/":{"url":"Leetcode/0142.Linked-List-CycleII/","title":"0142.Linked List Cycle II","summary":null,"keywords":"","body":"142. Linked List Cycle II tagsstart Medium Linked List Two Pointers tagsstop ้กŒ็›ฎ Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. Do not modify the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 Explanation: There is a cycle in the linked list, where tail connects to the second node. Example 2: Input: head = [1,2], pos = 0 Output: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list. Constraints: The number of the nodes in the list is in the range [0, 104]. -105 pos is -1 or a valid index in the linked-list. ้กŒ็›ฎๅคงๆ„ ๅทฒ็Ÿฅlinked list ไธญๆœ‰ๅซๆœ‰็’ฐ, ่ฟ”ๅ›ž้€™ๅ€‹็’ฐ็š„่ตทๅง‹ไฝ็ฝฎ ่งฃ้กŒๆ€่ทฏ ๅ‡่จญ็ฌฌไธ€ๆฌก็›ธ้‡, slow ่ตฐไบ†kๆญฅ, ้‚ฃ้บผ fastๅฐฑ่ตฐไบ† 2k, ไนŸๅฐฑๆ˜ฏ่ชชfastๆฏ”slowๅคš่ตฐไบ†kๆญฅ(็’ฐ้•ทๅบฆ็š„ๆ•ดๆ•ธๅ€) ่จญ็›ธ้‡้ปž่ˆ‡็’ฐ็š„่ตท้ปž่ท้›ข็‚บ m, ้‚ฃ้บผ็’ฐ็š„่ตท้ปž่ˆ‡Head็š„่ท้›ข็‚บ k-m ไพ†ๆบ https://leetcode.com/problems/linked-list-cycle-ii/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0142.Linked-List-CycleII/main.go package linkedlistcycleII /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } func DetectCycle(head *ListNode) *ListNode { fast, slow := head, head for fast != nil && fast.Next != nil { fast = fast.Next.Next slow = slow.Next if slow == fast { // ๆ‰พๅˆฐ็›ธ้‡้ปž break } } slow = head for slow != fast { fast = fast.Next slow = slow.Next } return slow } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0143.Reorder-List/":{"url":"Leetcode/0143.Reorder-List/","title":"143. Reorder List","summary":"0143.Reorder-List","keywords":"","body":"143. Reorder List tagsstart LeetCode Go /Medium 143. Reorder List Amazon Microsoft Adobe Facebook Bloomberg Linked List Two Pointers Stack Recursion tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : `` ็ฉบ้–“่ค‡้›œ : `` ไพ†ๆบ https://leetcode.com/problems/reorder-list/description/ https://leetcode.cn/problems/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0143.Reorder-List/main.go package reorderlist /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() // ๅ…ˆ็”จๅฟซๆ…ขๆŒ‡้‡ๆ‰พๅ‡บLinked list็š„ไธญ้–“้ปž // ็„ถๅพŒๆŠŠLinked listๅˆ†ๆˆๅ…ฉๅŠ // ๅ†ๆŠŠๅพŒๅŠ็š„Linked listๅ่ฝ‰ // ๅ†ๆŠŠๅ…ฉๅŠ็š„Linked list merge ่ตทไพ† func reorderList(head *ListNode) { mid := middleNode(head) // 2.ๅ่ฝ‰ไธญ้–“็ฏ€้ปž็š„ไธ‹ไธ€ๅ€‹็ฏ€้ปž right := resverseNode(mid.Next) mid.Next = nil left := head mergeNode(left, right) } // [876. Middle of the Linked List](https://leetcode.com/problems/middle-of-the-linked-list/) func middleNode(head *ListNode) *ListNode { slow, fast := head, head for fast != nil && fast.Next != nil { slow = slow.Next fast = fast.Next.Next } return slow } // [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) func resverseNode(head *ListNode) *ListNode { var pre *ListNode for head != nil { tmp := head.Next head.Next = pre pre = head head = tmp } return pre } func mergeNode(l1, l2 *ListNode) { lcur, rcur := l1, l2 for lcur != nil && rcur != nil { lcur.Next, rcur.Next, lcur, rcur = rcur, lcur.Next, lcur.Next, rcur.Next } } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/":{"url":"Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/","title":"0167.Two Sum II Input Array Is Sorted","summary":"0167.Two-Sum-II-Input-Array-Is-Sorted","keywords":"","body":"0167.Two Sum II Input Array Is Sorted tagsstart LeetCode Go Medium Two Sum II Input Array Is Sorted Array Two Pointers Binary Search tagsstop ้กŒ็›ฎ Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. Your solution must use only constant extra space. Example 1: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. Example 2: Input: numbers = [2,3,4], target = 6 Output: [1,3] Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. Example 3: Input: numbers = [-1,0], target = -1 Output: [1,2] Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. Constraints: 2 ้กŒ็›ฎๅคงๆ„ ๆ‰พๅ‡บๅ…ฉๅ€‹ๆ•ธไน‹ๅ’Œ็ญ‰ๆ–ผ target ็š„ๅ…ฉๅ€‹ๆ•ธไฝ๏ผŒ่ฆๆฑ‚่ผธๅ‡บๅฎƒๅ€‘็š„ไธ‹ๆจ™ใ€‚ ๆณจๆ„ไธ€ๅ€‹ๆ•ธไฝไธ่ƒฝไฝฟ็”จ 2 ๆฌกใ€‚ ไธ‹ๆจ™ๅพžๅฐๅˆฐๅคง่ผธๅ‡บใ€‚ ๅ‡ๅฎš้กŒ็›ฎไธ€ๅฎšๆœ‰ไธ€ๅ€‹่งฃใ€‚ ่งฃ้กŒๆ€่ทฏ Big O ไฝฟ็”จ1. Two Sunไพ†่งฃ O(n^2) ็š„ๆ™‚้–“่ค‡้›œๅบฆๅ’Œ O(1)็š„็ฉบ้–“่ค‡้›œๅบฆๆšดๅŠ› ่—‰ๅŠฉๅ“ˆๅธŒ่กจไฝฟ็”จ O(n) ็š„ๆ™‚้–“่ค‡้›œๅบฆๅ’Œ O(n) ็š„็ฉบ้–“่ค‡้›œๅบฆๆฑ‚่งฃ ้›™ๆŒ‡้‡ ๆ™‚้–“่ค‡้›œๅบฆ๏ผš O(n)๏ผŒๅ…ถไธญ n ๆ˜ฏ้™ฃๅˆ—็š„้•ทๅบฆใ€‚ ๅ…ฉๅ€‹ๆŒ‡ๆจ™็งปๅ‹•็š„็ธฝๆฌกๆ•ธๆœ€ๅคš็‚บ n ๆฌกใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ๏ผš O(1) ๆ™‚้–“่ค‡้›œ : ็ฉบ้–“่ค‡้›œ : ไพ†ๆบ https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ https://leetcode.cn/problems/two-sum-ii-input-array-is-sorted/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/main.go package twosumiiinputarrayissorted // ้›™ๆŒ‡้‡. ๆ™‚้–“่ค‡้›œๅบฆ๏ผš O(n)๏ผŒๅ…ถไธญ n ๆ˜ฏ้™ฃๅˆ—็š„้•ทๅบฆใ€‚ ๅ…ฉๅ€‹ๆŒ‡ๆจ™็งปๅ‹•็š„็ธฝๆฌกๆ•ธๆœ€ๅคš็‚บ n ๆฌกใ€‚ // ็ฉบ้–“่ค‡้›œๅบฆ๏ผš O(1) func TwoSum(numbers []int, target int) []int { left, right := 0, len(numbers)-1 for left Benchmark go test -benchmem -run=none LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz BenchmarkTwoSum-4 35161128 39.74 ns/op 16 B/op 1 allocs/op BenchmarkTwoSum2-4 19309680 70.21 ns/op 16 B/op 1 allocs/op PASS ok LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted 2.866s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0203.Remove-Linked-List-Elements/":{"url":"Leetcode/0203.Remove-Linked-List-Elements/","title":"0203.Remove Linked List Elements","summary":null,"keywords":"","body":"203. Remove Linked List Elements tagsstart Easy Linked List tagsstop ้กŒ็›ฎ Remove all elements from a linked list of integers that have value val. Example : Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5 ้กŒ็›ฎๅคงๆ„ ๅˆช้™ค้Š้Œถไธญๆ‰€ๆœ‰ๆŒ‡ๅฎšๅ€ผ็š„็ต้ปžใ€‚ ่งฃ้กŒๆ€่ทฏ ๆŒ‰็…ง้กŒๆ„ๅšๅณๅฏ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0203.Remove-Linked-List-Elements/ https://leetcode-cn.com/problems/remove-linked-list-elements/ https://mp.weixin.qq.com/s/slM1CH5Ew9XzK93YOQYSjA ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0203.Remove-Linked-List-Elements/Remove-Linked-List-Elements.go package removelinkedlistelements import ( \"LeetcodeGolang/structures\" ) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode = structures.ListNode // ๆ–นๆณ•ไธ€: ๅฆๅค–่€ƒๆ…ฎๅˆช้™คhead็ฏ€้ปž func RemoveElements(head *ListNode, val int) *ListNode { // ๅˆช้™คๅ€ผ็›ธๅŒ็š„head for head != nil && head.Val == val { head = head.Next } if head == nil { return head } tmpHead := head for tmpHead.Next != nil { if tmpHead.Next.Val == val { tmpHead.Next = tmpHead.Next.Next } else { tmpHead = tmpHead.Next } } return head } /* ๆ–นๆณ•ไบŒ ๆทปๅŠ ่™›ๆ“ฌ็ฏ€้ปž, ๆ•ˆ่ƒฝ่ผƒๅฅฝ ๅฏไปฅ่จญ็ฝฎไธ€ๅ€‹่™›ๆ“ฌ้ ญ็ต้ปžใ€๏ผŒ้€™ๆจฃๅŽŸ้Š้Œถ็š„ๆ‰€ๆœ‰็ฏ€้ปžๅฐฑ้ƒฝๅฏไปฅๆŒ‰็…ง็ตฑไธ€็š„ๆ–นๅผ้€ฒ่กŒ็งป้™คไบ† return newHead.Next */ func RemoveElementsVirtualNode(head *ListNode, val int) *ListNode { if head == nil { return head } // ๅปบ็ซ‹ไธ€ๅ€‹่™›ๆ“ฌ Head ็ฏ€้ปž newHead := &ListNode{Val: 0, Next: head} preHead := newHead curHead := head for curHead != nil { if curHead.Val == val { preHead.Next = curHead.Next } else { preHead = curHead } curHead = curHead.Next } return newHead.Next } /* ๆ–นๆณ•ไบŒ ้ž่ฟด */ func RemoveElementsRecurse(head *ListNode, val int) *ListNode { if head == nil { return head } head.Next = RemoveElementsRecurse(head.Next, val) if head.Val == val { return head.Next } else { return head } } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0206.Reverse-Linked-List/":{"url":"Leetcode/0206.Reverse-Linked-List/","title":"206. Reverse Linked List","summary":"Reverse Linked List","keywords":"","body":"206. Reverse Linked List tagsstart LeetCode Go Easy Reverse Linked List tagsstop ้กŒ็›ฎ Given the head of a singly linked list, reverse the list, and return the reversed list. Example 1: Input: head = [1,2,3,4,5] Output: [5,4,3,2,1] Example 2: Input: head = [1,2] Output: [2,1] Example 3: Input: head = [] Output: [] Constraints: The number of nodes in the list is the range [0, 5000]. -5000 Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? ้กŒ็›ฎๅคงๆ„ ๅฐ‡ Linked List ๅๅ‘ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://leetcode.com/problems/Reverse Linked List/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0000.kkkk/main.go package reverselinkedlist import ( . \"LeetcodeGolang/structures\" ) /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func ReverseList(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } var prev *ListNode for head != nil { next := head.Next head.Next = prev prev = head head = next } return prev } func ReverseListRecursively(head *ListNode) *ListNode { return ListRecursivelyChild(head, nil) } func ListRecursivelyChild(current *ListNode, prev *ListNode) *ListNode { if current == nil { return prev } next := current.Next current.Next = prev return ListRecursivelyChild(next, current) } Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0206.Reverse-Linked-List cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkReverseList-8 1000000000 0.7960 ns/op 0 B/op 0 allocs/op BenchmarkReverseListRecursively-8 276534334 4.374 ns/op 0 B/op 0 allocs/op PASS ok LeetcodeGolang/Leetcode/0206.Reverse-Linked-List 2.597s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0209.Minimum-Size-Subarray-Sum/":{"url":"Leetcode/0209.Minimum-Size-Subarray-Sum/","title":"0209. Minimum Size Subarray Sum","summary":null,"keywords":"","body":"209. Minimum Size Subarray Sum tagsstart Medium Sliding Window tagsstop ้ข˜็›ฎ Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum โ‰ฅ s. If there isn't one, return 0 instead. Example 1: Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint. Input: s = 4, nums = [1,4,4] Output: 1 Input: s = 11, nums = [1,1,1,1,1,1,1,1] Output: 0 Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n). ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆ•ดๅž‹ๆ•ธ็ต„ๅ’Œไธ€ๅ€‹ๆ•ธๅญ— s๏ผŒๆ‰พๅˆฐๆ•ธ็ต„ไธญๆœ€็Ÿญ็š„ไธ€ๅ€‹้€ฃ็บŒๅญๆ•ธ็ต„๏ผŒไฝฟๅพ—้€ฃ็บŒๅญๆ•ธ็ต„็š„ๆ•ธๅญ—ไน‹ๅ’Œ sum>=s๏ผŒ่ฟ”ๅ›žๆœ€็Ÿญ็š„้€ฃ็บŒๅญๆ•ธ็ต„็š„่ฟ”ๅ›žๅ€ผใ€‚ ่งฃ้กŒๆ€่ทฏ ้€™ไธ€้กŒ็š„่งฃ้กŒๆ€่ทฏๆ˜ฏ็”จๆป‘ๅ‹•็ช—ๅฃใ€‚ๅœจๆป‘ๅ‹•็ช—ๅฃ[i,j]ไน‹้–“ไธๆ–ทๅพ€ๅพŒ็งปๅ‹•๏ผŒๅฆ‚ๆžœ็ธฝๅ’Œๅฐๆ–ผs๏ผŒๅฐฑๆ“ดๅคงๅณ้‚Š็•Œj๏ผŒไธๆ–ทๅŠ ๅ…ฅๅณ้‚Š็š„ๅ€ผ๏ผŒ็›ดๅˆฐsum > s๏ผŒไน‹ๅ’Œๅ†็ธฎๅฐi ็š„ๅทฆ้‚Š็•Œ๏ผŒไธๆ–ท็ธฎๅฐ็›ดๅˆฐsum ้€ฒ้šŽ ๅฆ‚ๆžœไฝ ๅทฒ็ถ“ๅฏฆ็พ O(n) ๆ™‚้–“่ค‡้›œๅบฆ็š„่งฃๆณ•, ่ซ‹ๅ˜—่ฉฆ่จญ่จˆไธ€ๅ€‹ O(n log(n)) ๆ™‚้–“่ค‡้›œๅบฆ็š„่งฃๆณ•ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0209.Minimum-Size-Subarray-Sum/ https://leetcode-cn.com/problems/minimum-size-subarray-sum/ https://mp.weixin.qq.com/s/UrZynlqi4QpyLlLhBPglyg ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0209.Minimum-Size-Subarray-Sum/Minimum-Size-Subarray-Sum.go package minimumsizesubarraysum import ( \"math\" \"sort\" ) // MinSubArrayLenBurst : ๆšดๅŠ›่งฃ ๆ™‚้–“่ค‡้›œ O(n^2), ็ฉบ้–“่ค‡้›œ O(1) func MinSubArrayLenBurst(target int, nums []int) int { lens := len(nums) if lens = target { minSize = min(minSize, j-i+1) } } } if minSize == math.MaxInt32 { minSize = 0 } return minSize } // MinSubArrayLenSlidingWindow : ๆป‘ๅ‹•่ฆ–็ช— ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) // ๆป‘ๅ‹•็ช—ๅฃ็š„็ฒพๅฆ™ไน‹่™•ๅœจๆ–ผๆ นๆ“š็•ถๅ‰ๅญๅบๅˆ—ๅ’Œๅคงๅฐ็š„ๆƒ…ๆณ๏ผŒไธๆ–ท่ชฟ็ฏ€ๅญๅบๅˆ—็š„่ตทๅง‹ไฝ็ฝฎใ€‚ๅพž่€Œๅฐ‡O(n^2)็š„ๆšดๅŠ›่งฃๆณ•้™็‚บO(n) func MinSubArrayLenSlidingWindow(target int, nums []int) int { lens := len(nums) if lens = target { minSize = min(minSize, end-start+1) sum -= nums[start] start++ } end++ } if minSize == math.MaxInt32 { minSize = 0 } return minSize } /* MinSubArrayLenBinarysearch : ๅ‰็ผ€ๅ’Œ + ไบŒๅˆ†ๆŸฅๆ‰พ O(nlog(n)) ็‚บไบ†ไฝฟ็”จไบŒๅˆ†ๆŸฅๆ‰พ๏ผŒ้œ€่ฆ้กๅค–ๅ‰ตๅปบไธ€ๅ€‹ๆ•ธ็ต„ sums ็”จๆ–ผๅญ˜ๅ„ฒๆ•ธ็ต„nums ็š„ๅ‰็ถดๅ’Œ๏ผŒๅ…ถไธญ sums[i] ่กจ็คบๅพž nums[0] ๅˆฐ nums[iโˆ’1] ็š„ๅ…ƒ็ด ๅ’Œใ€‚ ๅพ—ๅˆฐๅ‰็ถดๅ’Œไน‹ๅพŒ๏ผŒๅฐๆ–ผๆฏๅ€‹้–‹ๅง‹ไธ‹ๆจ™i๏ผŒๅฏ้€š้ŽไบŒๅˆ†ๆŸฅๆ‰พๅพ—ๅˆฐๅคงๆ–ผๆˆ–็ญ‰ๆ–ผ i ็š„ๆœ€ๅฐไธ‹ๆจ™ bound๏ผŒ ไฝฟๅพ— sums[bound]-sums[i-1] >= s๏ผŒ ไธฆๆ›ดๆ–ฐๅญๆ•ธ็ต„็š„ๆœ€ๅฐ้•ทๅบฆ๏ผˆๆญคๆ™‚ๅญๆ•ธ็ต„็š„้•ทๅบฆๆ˜ฏ bound -(i-1) )ใ€‚ C++ ็š„ lower_bound๏ผŒJava ็š„ Arrays.binarySearch ๅ› ็‚บ้€™้“้กŒไฟ่ญ‰ไบ†ๆ•ธ็ต„ไธญๆฏๅ€‹ๅ…ƒ็ด ้ƒฝ็‚บๆญฃ๏ผŒๆ‰€ไปฅๅ‰็ถดๅ’Œไธ€ๅฎšๆ˜ฏ้žๅขž็š„๏ผŒ้€™ไธ€้ปžไฟ่ญ‰ไบ†ไบŒๅˆ†็š„ๆญฃ็ขบๆ€งใ€‚ๅฆ‚ๆžœ้กŒ็›ฎๆฒ’ๆœ‰่ชชๆ˜Žๆ•ธ็ต„ไธญๆฏๅ€‹ๅ…ƒ็ด ้ƒฝ็‚บๆญฃ๏ผŒ้€™่ฃกๅฐฑไธ่ƒฝไฝฟ็”จไบŒๅˆ†ไพ†ๆŸฅๆ‰พ้€™ๅ€‹ไฝ็ฝฎไบ†ใ€‚ */ func MinSubArrayLenBinarysearch(target int, nums []int) int { lens := len(nums) if lens ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0215.Kth-Largest-Element-in-an-Array/":{"url":"Leetcode/0215.Kth-Largest-Element-in-an-Array/","title":"0215. Kth Largest Element in an Array","summary":"Kth Largest Element in an Array","keywords":"","body":"0215. Kth Largest Element in an Array tagsstart LeetCode Go Medium Kth Largest Element in an Array Heap Priority Queue Sorting tagsstop ้กŒ็›ฎ Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. Can you solve it without sorting? Example 1: Input: nums = [3,2,1,5,6,4], k = 2 Output: 5 Example 2: Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 Output: 4 Constraints: 1 -104 ้กŒ็›ฎๅคงๆ„ ๆ•ธ็ต„ไธญ็š„็ฌฌKๅ€‹ๆœ€ๅคงๅ…ƒ็ด  (Kth Largest Element in an Array) ็ตฆๅฎšไธ€ๅ€‹ๆœชๆŽ’ๅบ็š„ๆ•ดๆ•ธๆ•ธ็ต„๏ผŒๆ‰พๅˆฐๅ…ถไธญ็ฌฌKๅ€‹ๆœ€ๅคง็š„ๅ…ƒ็ด ใ€‚ ่งฃ้กŒๆ€่ทฏ ไธ€็จฎๅธธ่ฆ‹็š„่งฃๆณ•ๆ˜ฏไฝฟ็”จๅ †ๆ•ธๆ“š็ตๆง‹ใ€‚ๆˆ‘ๅ€‘ๅฏไปฅ็ถญ่ญทไธ€ๅ€‹ๅคงๅฐ็‚บK็š„ๆœ€ๅฐๅ †๏ผŒๅˆๅง‹ๆ™‚ๅฐ‡ๆ•ธ็ต„็š„ๅ‰Kๅ€‹ๅ…ƒ็ด ๅŠ ๅ…ฅๅ †ไธญใ€‚็„ถๅพŒ้ๆญทๆ•ธ็ต„็š„ๅ‰ฉ้ค˜ๅ…ƒ็ด ๏ผŒๅฆ‚ๆžœ็•ถๅ‰ๅ…ƒ็ด ๆฏ”ๅ †้ ‚ๅ…ƒ็ด ๅคง๏ผŒๅ‰‡ๅฐ‡ๅ †้ ‚ๅ…ƒ็ด ๅ‡บๅ †๏ผŒไธฆๅฐ‡็•ถๅ‰ๅ…ƒ็ด ๅŠ ๅ…ฅๅ †ไธญใ€‚ๆœ€ๅพŒๅ †้ ‚ๅ…ƒ็ด ๅณ็‚บ็ฌฌKๅ€‹ๆœ€ๅคง็š„ๅ…ƒ็ด ใ€‚ ๆ™‚้–“่ค‡้›œๅบฆ: ๆง‹ๅปบๅ †็š„ๆ™‚้–“่ค‡้›œๅบฆ็‚บO(K)๏ผŒ้ๆญทๆ•ธ็ต„็š„ๆ™‚้–“่ค‡้›œๅบฆ็‚บO((N-K)logK)๏ผŒๅ› ๆญค็ธฝ็š„ๆ™‚้–“่ค‡้›œๅบฆ็‚บO(NlogK)ใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ: ไฝฟ็”จไบ†ๅคงๅฐ็‚บK็š„ๆœ€ๅฐๅ †ไพ†ๅญ˜ๅ„ฒๅ…ƒ็ด ๏ผŒๅ› ๆญค็ฉบ้–“่ค‡้›œๅบฆ็‚บO(K)ใ€‚ ๅœจๅฟซ้€Ÿ้ธๆ“‡ quickselect ็š„ partition ๆ“ไฝœไธญ๏ผŒๆฏๆฌก partition ๆ“ไฝœ็ตๆŸ้ƒฝๆœƒ่ฟ”ๅ›žไธ€ๅ€‹้ปž๏ผŒ้€™ๅ€‹ๆจ™ๅฎš้ปž็š„ไธ‹ๆจ™ๅ’Œๆœ€็ต‚ๆŽ’ๅบไน‹ๅพŒๆœ‰ๅบๆ•ธ็ต„ไธญ้€™ๅ€‹ๅ…ƒ็ด ๆ‰€ๅœจ็š„ไธ‹ๆจ™ๆ˜ฏไธ€่‡ด็š„ใ€‚ๅˆฉ็”จ้€™ๅ€‹็‰นๆ€ง๏ผŒๆˆ‘ๅ€‘ๅฏไปฅไธๆ–ท็š„ๅŠƒๅˆ†ๆ•ธ็ต„ๅ€้–“๏ผŒๆœ€็ต‚ๆ‰พๅˆฐ็ฌฌ K ๅคง็š„ๅ…ƒ็ด ใ€‚ๅŸท่กŒไธ€ๆฌก partition ๆ“ไฝœไปฅๅพŒ๏ผŒๅฆ‚ๆžœ้€™ๅ€‹ๅ…ƒ็ด ็š„ไธ‹ๆจ™ๆฏ” K ๅฐ๏ผŒ้‚ฃ้บผๆŽฅ่‘—ๅฐฑๅœจๅพŒ้‚Š็š„ๅ€้–“็นผ็บŒๅŸท่กŒ partition ๆ“ไฝœ๏ผ›ๅฆ‚ๆžœ้€™ๅ€‹ๅ…ƒ็ด ็š„ไธ‹ๆจ™ๆฏ” K ๅคง๏ผŒ้‚ฃ้บผๅฐฑๅœจๅทฆ้‚Š็š„ๅ€้–“็นผ็บŒๅŸท่กŒ partition ๆ“ไฝœ๏ผ›ๅฆ‚ๆžœ็›ธ็ญ‰ๅฐฑ็›ดๆŽฅ่ผธๅ‡บ้€™ๅ€‹ไธ‹ๆจ™ๅฐๆ‡‰็š„ๆ•ธ็ต„ๅ…ƒ็ด ๅณๅฏใ€‚ ๅฟซ้€Ÿ้ธๆ“‡ quickselect ็š„ๆ€่ทฏๅฏฆ็พ็š„็ฎ—ๆณ•ๆ™‚้–“่ค‡้›œๅบฆ็‚บ O(n)๏ผŒ็ฉบ้–“่ค‡้›œๅบฆ็‚บ O(logn) ไพ†ๆบ https://leetcode.com/problems/kth-largest-element-in-an-array/ https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0215.Kth-Largest-Element-in-an-Array/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0215.Kth-Largest-Element-in-an-Array/main.go package kthlargestelementinanarray import ( \"container/heap\" \"sort\" ) // ่งฃๆณ•ไธ€๏ผš็”จHeap่ณ‡ๆ–™็ตๆง‹ // container/heapๅŒ…ๅฏไปฅ็”จๆฅๆง‹้€ ๅ„ชๅ…ˆ็ดšQueueใ€‚ // Heap(ๅ †็ฉ)ๅ…ถๅฏฆๆ˜ฏไธ€ๅ€‹Complete Binary Tree(ๅฎŒๅ…จไบŒๅ…ƒๆจน). // Go็š„Heap็‰นๆ€งๆ˜ฏ ๅ„ๅ€‹็ฏ€้ปž้ƒฝ่‡ชๅทฑๆ˜ฏๅ…ถๅญๆจน็š„ๆ น, ไธ”ๅ€ผๆ˜ฏๆœ€ๅฐ็š„(index = 0 ็š„ๅ€ผๆ˜ฏๆœ€ๅฐ็š„). // ๅŒๅ€‹ๆ น็ฏ€้ปž็š„ๅทฆๅญๆจน็š„ๅ€ผๆœƒๅฐๆ–ผๅณๅญๆจน func FindKthLargestHeap(nums []int, k int) int { if k len(nums) { return 0 } // ๅˆๅง‹ๅŒ–ๆœ€ๅฐๅ † h := &MinHeap{} heap.Init(h) // ้ๆญท้›†ๅˆ for _, num := range nums { if h.Len() (*h)[0] { heap.Pop(h) heap.Push(h, num) } } // fmt.Println(h) return (*h)[0] } // ่‡ชๅฎš็พฉๆœ€ๅฐ Heap ็ตๆง‹้ซ” type MinHeap []int func (h MinHeap) Len() int { return len(h) } func (h MinHeap) Less(i, j int) bool { // ๅฐๅˆฐๅคงๆŽ’ๅบ return h[i] Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkFindKthLargestHeap-8 6112726 184.9 ns/op 48 B/op 3 allocs/op BenchmarkFindKthLargestSort-8 18023403 60.38 ns/op 24 B/op 1 allocs/op PASS ok LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array 3.383s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0217.Contains-Duplicate/":{"url":"Leetcode/0217.Contains-Duplicate/","title":"0217.Contains-Duplicate","summary":"Contains Duplicate","keywords":"","body":"0217.Contains-Duplicate tagsstart LeetCode Go Easy Contains Duplicate Array Blind75 tagsstop ้กŒ็›ฎ 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 Example 2: Input: nums = [1,2,3,4] Output: false Example 3: Input: nums = [1,1,1,3,3,4,3,2,4,2] Output: true Constraints: 1 -109 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://leetcode.com/problems/contains-duplicate/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0217.Contains-Duplicate/main.go package containsduplicate func ContainsDuplicate(nums []int) bool { numsMap := make(map[int]bool, len(nums)) for _, v := range nums { if numsMap[v] { return true } numsMap[v] = true } return false } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0226.Invert-Binary-Tree/":{"url":"Leetcode/0226.Invert-Binary-Tree/","title":"226. Invert Binary Tree","summary":"226. Invert Binary Tree","keywords":"","body":"226. Invert Binary Tree tagsstart LeetCode Go Easy Invert Binary Tree BFS tagsstop ้กŒ็›ฎ Given the root of a binary tree, invert the tree, and return its root. Example 1: Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1] Example 2: Input: root = [2,1,3] Output: [2,3,1] Example 3: Input: root = [] Output: [] Constraints: The number of nodes in the tree is in the range [0, 100]. -100 ้กŒ็›ฎๅคงๆ„ ๅ่ฝ‰ไบŒๅ‰ๆจน ่งฃ้กŒๆ€่ทฏ ็”จ้žๆญธไพ†่งฃๆฑบ๏ผŒๅ…ˆ้žๆญธ่ชฟ็”จๅ่ฝ‰ๆ น็ฏ€้ปž็š„ๅทฆchildren๏ผŒ็„ถๅพŒ้žๆญธ่ชฟ็”จๅ่ฝ‰ๆ น็ฏ€้ปž็š„ๅณchildren๏ผŒ็„ถๅพŒๅทฆๅณไบคๆ›ๆ น็ฏ€้ปž็š„ๅทฆchildrenๅ’Œๅณchildrenใ€‚ ๆœ‰้ปžๅƒๆ˜ฏBFS BFS๏ผˆๅปฃๅบฆๅ„ชๅ…ˆๆœ็ดข๏ผ‰ๅ‰‡ไฝฟ็”จ้šŠๅˆ—๏ผˆQueue๏ผ‰ไพ†ๅฏฆ็พใ€‚ๅœจBFSไธญ๏ผŒๆ‚จ้ฆ–ๅ…ˆ่™•็†ไธ€ๅ€‹็ฏ€้ปž๏ผŒ็„ถๅพŒๅฐ‡ๅ…ถๅญ็ฏ€้ปžๆŒ‰ๆŸ็จฎ้ †ๅบๆŽ’้šŠ๏ผŒๆŽฅ่‘—็นผ็บŒ่™•็†้šŠๅˆ—็š„ๅ‰็ซฏ็ฏ€้ปž๏ผŒ็›ดๅˆฐ้šŠๅˆ—็‚บ็ฉบใ€‚ ไพ†ๆบ https://leetcode.com/problems/invert-binary-tree/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0226.Invert-Binary-Tree/main.go package invertbinarytree import ( \"LeetcodeGolang/Utility/structures\" ) /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ // type TreeNode struct { // Val int // Left *TreeNode // Right *TreeNode // } func InvertTree(root *structures.TreeNode) *structures.TreeNode { if root == nil { return nil } InvertTree(root.Left) InvertTree(root.Right) root.Left, root.Right = root.Right, root.Left return root } func InvertTree2(root *structures.TreeNode) *structures.TreeNode { if root != nil { root.Left, root.Right = InvertTree2(root.Right), InvertTree2(root.Left) } return root } func InvertTree3(root *structures.TreeNode) *structures.TreeNode { queue := make([]*structures.TreeNode, 0) queue = append(queue, root) for len(queue) > 0 { current := queue[0] queue = queue[1:] current.Left, current.Right = current.Right, current.Left if current.Left != nil { queue = append(queue, current.Left) } if current.Right != nil { queue = append(queue, current.Right) } } return root } func BuildTree(nums []int, index int) *TreeNode { if index >= len(nums) || nums[index] == -1 { return nil } root := &TreeNode{Val: nums[index]} root.Left = BuildTree(nums, 2*index+1) root.Right = BuildTree(nums, 2*index+2) return root } func IntsToTree(nums []int) *TreeNode { return BuildTree(nums, 0) } Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkInvertTree-8 2533011 398.7 ns/op 168 B/op 7 allocs/op BenchmarkInvertTree2-8 2667645 392.4 ns/op 168 B/op 7 allocs/op BenchmarkInvertTree3-8 1403001 727.5 ns/op 296 B/op 13 allocs/op PASS ok LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree 4.889s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0238.Product-of-Array-Except-Self/":{"url":"Leetcode/0238.Product-of-Array-Except-Self/","title":"238. Product of Array Except Self","summary":"0238.Product-of-Array-Except-Self","keywords":"","body":"238. Product of Array Except Self tagsstart LeetCode Go Medium Product of Array Except Self Array Prefix Sum Blind75 tagsstop ้กŒ็›ฎ Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Example 1: Input: nums = [1,2,3,4] Output: [24,12,8,6] Example 2: Input: nums = [-1,1,0,-3,3] Output: [0,0,9,0,0] Constraints: 2 Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.) ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : `` ไพ†ๆบ https://leetcode.com/problems/product-of-array-except-self/description/ https://leetcode.cn/problems/product-of-array-except-self/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0238.Product-of-Array-Except-Self/main.go package productofarrayexceptself // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() func productExceptSelf(nums []int) []int { result, left, right := make([]int, len(nums)), make([]int, len(nums)), make([]int, len(nums)) // left ็‚บๅทฆๅดๆ‰€ๆœ‰็š„ๆˆ็ธพ // ็ดขๅผ•็‚บ'0' ็š„ๅ…ƒ็ด , ๅ› ็‚บๅทฆๅดๆฒ’ๆœ‰ๅ…ƒ็ด ,ๆ‰€ไปฅleft[0]=1 left[0] = 1 for i := 1; i = 0; i-- { right[i] = right[i+1] * nums[i+1] } for i := 0; i = 0; i-- { result[i] = result[i] * rightProduct rightProduct = rightProduct * nums[i] } return result } Benchmark go test -benchmem -run=none LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkProductExceptSelf-8 12772174 158.4 ns/op 96 B/op 3 allocs/op BenchmarkProductExceptSelf2-8 32292304 63.74 ns/op 32 B/op 1 allocs/op PASS ok LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self 4.228s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0242.Valid-Anagram/":{"url":"Leetcode/0242.Valid-Anagram/","title":"0242.Valid-Anagram","summary":"Valid Anagram","keywords":"","body":"0242.Valid-Anagram tagsstart LeetCode Go Easy Valid Anagram tagsstop ้ฉ—่ญ‰ๅ›žๆ–‡ไธฒ ้กŒ็›ฎ Given two strings s and t, return true if t is an anagram of s, and false otherwise. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: s = \"anagram\", t = \"nagaram\" Output: true Example 2: Input: s = \"rat\", t = \"car\" Output: false Constraints: 1 Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case? ๆˆ‘ๅ€‘ไฝฟ็”จ rune ๆ•ธๆ“š้กžๅž‹ไพ†่™•็† Unicode ๅญ—ๅ…ƒ๏ผŒไธฆไฝฟ็”จ map[rune]int ไพ†็ตฑ่จˆ้€™ไบ›ๅญ—็ฌฆ็š„ๅ‡บ็พๆฌกๆ•ธใ€‚ๅ…ถ้ค˜็š„้‚่ผฏไฟๆŒไธ่ฎŠใ€‚ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ๅช่ฆๅ…ˆๆŠŠๆ‰€ๆœ‰ๅญ—็ฌฆ่ฝ‰ๆ›ๆˆๅฐๅฏซ๏ผŒไธฆ้ŽๆฟพๆŽ‰็ฉบๆ ผๅ’Œๆจ™้ปž้€™้กžๅญ—็ฌฆ๏ผŒ็„ถๅพŒๅฐๅ‰ฉไธ‹็š„ๅญ—็ฌฆๅŸท่กŒ ๆ•ธ็ต„้›™ๆŒ‡้‡ๆŠ€ๅทงๅŒฏ็ธฝ ไธญๆๅˆฐ็š„ๅ…ฉ็ซฏๅ‘ไธญๅฟƒ็š„้›™ๆŒ‡้‡ๆผ”็ฎ—ๆณ•ๅณๅฏ ไพ†ๆบ https://leetcode.com/problems/valid-anagram/description/ https://leetcode.cn/problems/valid-anagram/description/ ๆ•ธ็ต„้›™ๆŒ‡้‡ๆŠ€ๅทงๅŒฏ็ธฝ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0242.Valid-Anagram/main.go package validanagram func IsAnagram(s string, t string) bool { if len(s) != len(t) { return false } record := make(map[rune]int, len(s)) for _, v := range s { record[v]++ } for _, v := range t { record[v]-- if record[v] Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0242.Valid-Anagram cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkIsAnagram-8 6703497 276.3 ns/op 0 B/op 0 allocs/op BenchmarkIsAnagram2-8 3660909 318.9 ns/op 48 B/op 2 allocs/op PASS ok LeetcodeGolang/Leetcode/0242.Valid-Anagram 4.498s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0283.Move-Zeroes/":{"url":"Leetcode/0283.Move-Zeroes/","title":"0283. Move Zeroes","summary":"0283. Move Zeroes","keywords":"","body":"283. Move Zeroes tagsstart LeetCode Go Easy Move Zeroes tagsstop ้กŒ็›ฎ Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. Example 1: Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2: Input: nums = [0] Output: [0] Constraints: 1 -231 Follow up: Could you minimize the total number of operations done? ้กŒ็›ฎๅคงๆ„ ้กŒ็›ฎ่ฆๆฑ‚ไธ่ƒฝๅˆฉ็”จ้กๅค–็š„่ผ”ๅŠฉ็ฉบ้–“๏ผŒๅฐ‡ๆ•ธๅญ—็ต„ไธญ 0 ๅ…ƒ็ด ้ƒฝ็งปๅˆฐๆ•ธๅญ—็ต„็š„ๆœซๅฐพ๏ผŒไธฆ่ˆ‡็ถญๆŒๆ‰€ๆœ‰้ž 0 ๅ…ƒ็ด ็š„็›ธๅฐไฝ็ฝฎใ€‚ ่งฃ้กŒๆ€่ทฏ ้ž้›ถไบคๆ›ๆ•ธๆ“š, ๅทฆๅณๆŒ‡้‡้ƒฝๅพ€ๅณ็งป ้›ถ, ๅณๆŒ‡้‡ๅณ็งป ไพ†ๆบ https://leetcode.com/problems/move-zeroes/ https://books.halfrost.com/leetcode/ChapterFour/0200~0299/0283.Move-Zeroes/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0283.Move-Zeroes/main.go package movezeroes // ๆ™‚้–“O(n^2) func MoveZeroes(nums []int) { for i := 0; i Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0283.Move-Zeroes cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz BenchmarkMoveZeroes-4 145544966 9.164 ns/op 0 B/op 0 allocs/op BenchmarkMoveZeroes2point-4 183269922 6.149 ns/op 0 B/op 0 allocs/op PASS ok LeetcodeGolang/Leetcode/0283.Move-Zeroes 3.975s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0300.Longest-Increasing-Subsequence/":{"url":"Leetcode/0300.Longest-Increasing-Subsequence/","title":"0300.Longest Increasing Subsequence","summary":null,"keywords":"","body":"300.Longest-Increasing-Subsequence tagsstart Medium Dynamic Programming Patience Sorting Binary Search tagsstop ๆœ€้•ท้žๅขžๅญๅบๅˆ—(Longest Increasing Subsequence, LIS) ้กŒ็›ฎ Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Example 1: Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. Example 2: Input: nums = [0,1,0,3,2,3] Output: 4 Example 3: Input: nums = [7,7,7,7,7,7,7] Output: 1 Constraints: 1 -104 Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity? ้กŒ็›ฎๅคงๆ„ ็ตฆไฝ ไธ€ๅ€‹ๆ•ดไบ‹็š„ๆ•ธ็ต„ nums\b\b, ๆ‰พๅˆฐๅ…ถไธญๆœ€้•ท้žๅขžๅญๅบๅˆ—็š„้•ทๅบฆ ๅญๅบๅˆ—ไธไธ€ๅฎšๆ˜ฏ้€ฃ็บŒ็š„ ๅญไธฒไธ€ๅฎšๆ˜ฏ้€ฃ็บŒ็š„ ่งฃ้กŒๆ€่ทฏ ๆ–นๆณ•ไธ€: DP dp[i]่กจ็คบnums[i]้€™ๅ€‹ๆ•ธ็ตๅฐพ็š„ๆœ€้•ท้žๅขžๅญๅบๅˆ—็š„้•ทๅบฆ ่ญฌๅฆ‚่ฆๆ‰พdp[5]็š„็›ด, ไนŸๅฐฑๆ˜ฏ็ƒnums[5]็‚บ็ตๅฐพ็š„ๆœ€้•ท้žๅขžๅญๅบๅˆ— ๅช่ฆๆ‰พๅˆฐ็ตๅฐพๆฏ”nums[5]ๅฐ็š„ๅญๅบๅˆ—, ็„ถๅพŒๆŠŠ nums[5]ๆŽฅๅˆฐๆœ€ๅพŒ, ๅฐฑๅฏไปฅๅฝขๆˆๆ–ฐ็š„้žๅขžๅญๅบๅˆ—, ่€Œ้€™ๅ€‹ๆ–ฐๅญๅบๅˆ—้•ทๅบฆ+1 ๆ–นๆณ•ไบŒ: DP + ไบŒๅˆ†ๆœๅฐ‹ patience sorting (่€ๅฟƒๆŽ’ๅบ) ็ตฆไธ€็ต„ [6, 3 ,5 ,10, 11, 2, 9, 14, 13, 7, 4, 8, 12] ๅช่ƒฝๆŠŠๆ•ธๅญ—ๅฐ็š„ๆ”พๅœจๆ•ธๅญ—ๅคง็š„ๅ †ไธŠ, ๅฆ‚ๆžœ็•ถๅ‰ๆ•ธๅญ—ๅคชๅคงๆฒ’ๆœ‰ๅฏไปฅๆ”พ็ฝฎ็š„ๅ †, ๅ‰‡ๆ–ฐๅปบไธ€ๅ€‹ๅ †, ๅฆ‚ๆžœ็•ถๅ‰ๆŽ’ๆœ‰ๅพˆๅคšๅ †ๅฏไปฅ้ธๆ“‡, ๅ‰‡้ธๆ“‡ๆœ€ๅทฆ้‚Š็š„้‚ฃไธ€ๅ †ๆ”พ, ๅ› ็‚บ้€™ๆจฃๅฏไปฅ็ขบไฟๅ †้ ‚ๆ˜ฏๆœ‰ๅบ็š„(2,4,7,8,12) 6 5 10 11 14 3 4 9 8 13 2 7 12 ๅ †ๆ•ธๅฐฑๆ˜ฏๆœ€้•ท้žๅขžๅญๅบๅˆ—็š„้•ทๅบฆ [3,5,7,8,12] ไพ†ๆบ https://leetcode.com/problems/longest-increasing-subsequence/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0300.Longest-Increasing-Subsequence/main.go package longestincreasingsubsequence import \"fmt\" func max(a, b int) int { if a > b { return a } return b } // DP ่งฃๆณ• O(n^2) func LengthOfLIS(nums []int) int { dp := make([]int, len(nums)) for idx := 0; idx nums[j] { // ๆ‰พๅˆฐไธ‹ไธ€ๅ€‹ๆ•ธๅ€ผๆฏ”็พๅœจ็š„ๅคง dp[i] = max(dp[i], dp[j]+1) } } res = max(res, dp[i]) } // fmt.Println(dp) return res } func LengthOfLIS2(nums []int) int { dp := make([]int, len(nums)+1) dp[0] = 0 res := 0 for i := 1; i nums[j-1] { // ๆ‰พๅˆฐๅ‰้ขๆฏ”็พๅœจ็ตๅฐพ้‚„ๅฐ็š„ๅญๅบๅˆ— dp[i] = max(dp[i], dp[j]) } } dp[i] = dp[i] + 1 res = max(res, dp[i]) } // fmt.Println(dp) return res } // DP + ไบŒๅˆ†ๆœๅฐ‹:patience sorting. O(nlogn) func LengthOfLISPatience(nums []int) int { top := make([]int, len(nums)) // ็‰Œๅ †ๆ•ธๅˆๅง‹ๅŒ–็‚บ0 piles := 0 for i := 0; i poker { // ็พๅœจ็š„็‰Œๆฏ”ๅ †ๅฐ, ็ธฎๅฐ็ฏ„ๅœ right = mid } else if top[mid] go test -benchmem -run=none LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkLengthOfLIS-8 18300901 64.77 ns/op 64 B/op 1 allocs/op BenchmarkLengthOfLIS2-8 17410562 68.98 ns/op 80 B/op 1 allocs/op BenchmarkLengthOfLISPatience-8 20768851 58.47 ns/op 64 B/op 1 allocs/op PASS ok LeetcodeGolang/Leetcode/300.Longest-Increasing-Subsequence 3.812s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0310.Minimum-Height-Trees/":{"url":"Leetcode/0310.Minimum-Height-Trees/","title":"0310.Minimum Height Trees","summary":null,"keywords":"","body":"310. Minimum Height Trees tagsstart Medium Breadth First Search tagsstop ้กŒ็›ฎ A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf. Example 1: Input: n = 4, edges = [[1,0],[1,2],[1,3]] Output: [1] Explanation: As shown, the height of the tree is 1 when the root is the node with label 1 which is the only MHT. Example 2: Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] Output: [3,4] Constraints: 1 edges.length == n - 1 0 ai != bi All the pairs (ai, bi) are distinct. The given input is guaranteed to be a tree and there will be no repeated edges. ้กŒ็›ฎๅคงๆ„ ่ผธๅ…ฅไธ€ๅ€‹nๅ€‹็ฏ€้ปž็š„ไบŒๅ‰ๆจน, ่จˆ็ฎ—ๅ‡บๆœ€ๅฐ้ซ˜ๅบฆ(rootๅˆฐleft็š„ๆœ€็Ÿญ่ท้›ข) ่งฃ้กŒๆ€่ทฏ ็”จBFSไพ†่งฃ. Queue ่ตท้ปžๅฐฑๆ˜ฏroot, ็ต‚้ปžๅฐฑๆ˜ฏๆœ€้ ่ฟ‘root็š„้‚ฃๅ€‹่‘‰็ฏ€้ปž(ๅฐฑๆ˜ฏๅ…ฉๅ€‹ๅญ็ฏ€้ปž้ƒฝๆ˜ฏnull) ไพ†ๆบ https://leetcode.com/problems/minimum-height-trees/ https://leetcode-cn.com/problems/minimum-height-trees/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0310.Minimum-Height-Trees/main.go package minimumheighttrees import \"fmt\" func FindMinHeightTrees(n int, edges [][]int) []int { if n == 1 { return []int{0} } graph := make(map[int][]int) degree := make(map[int]int, n) //ๅ‡บๅบฆ: ๅ‡บๅบฆๆ˜ฏๆŒ‡ๅพž่ฉฒ็ฏ€้ปž๏ผˆ้ ‚้ปž๏ผ‰ๅ‡บ็™ผ็š„้‚Š็š„ๆขๆ•ธ // ๅปบ็ซ‹ๅฐๆ‡‰้—œไฟ‚ for _, v := range edges { if _, ok := graph[v[0]]; ok { graph[v[0]] = append(graph[v[0]], v[1]) } else { // ๆฒ’ๆ‰พๅˆฐ graph[v[0]] = []int{v[1]} } if _, ok := graph[v[1]]; ok { graph[v[1]] = append(graph[v[1]], v[0]) } else { // ๆฒ’ๆ‰พๅˆฐ graph[v[1]] = []int{v[0]} } degree[v[0]]++ degree[v[1]]++ } fmt.Printf(\"graph: %+v \\n\", graph) fmt.Printf(\"degree: %+v \\n\", degree) var queue []int for key, value := range degree { //ๅ…ˆๆ‰พๅˆฐๅ‡บๅบฆ็‚บ1็š„้ปž, ๅŠ ๅˆฐQueue if value == 1 { queue = append(queue, key) } } fmt.Printf(\"queue: %+v \\n\", queue) leaves := []int{} for len(queue) != 0 { leaves = leaves[0:0] size := len(queue) for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0322.Coin-Change/":{"url":"Leetcode/0322.Coin-Change/","title":"0322.Coin Change","summary":"0322.Coin Change","keywords":"","body":"322. Coin Change tagsstart LeetCode Go Coin Change Medium Dynamic Programming tagsstop ้กŒ็›ฎ You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. Example 1: Input: coins = [1,2,5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1 Example 2: Input: coins = [2], amount = 3 Output: -1 Example 3: Input: coins = [1], amount = 0 Output: 0 Constraints: 1 ้กŒ็›ฎๅคงๆ„ ็ตฆๅฆณ k ็จฎ้ขๅ€ผ็š„็กฌๅนฃ, ้ขๅ€ผๅˆ†ๅˆฅ็‚บ c1,c2 ...,ck, ๆฏ็จฎ็กฌๅนฃ็š„ๆ•ธ้‡็„ก้™. ๅ†็ตฆไฝ ไธ€ๅ€‹็ธฝ้‡‘้ก. ๆฑ‚ๅ‡บๆœ€ๅฐ‘ ้œ€่ฆๅนพๆžš็กฌๅนฃๆนŠๅ‡บ้€™ๅ€‹้‡‘้ก, ๅฆ‚ๆžœไธ่ƒฝๆนŠๅ‡บ return -1. ่งฃ้กŒๆ€่ทฏ dp(n) ็š„ๅฎš็พฉ: ่ผธๅ…ฅไธ€ๅ€‹็›ฎๆจ™้‡‘้กn, ่ฟ”ๅ›žๆนŠๅ‡บ็›ฎๆจ™้‡‘้กn็š„ๆœ€ๅฐ‘็กฌๅนฃๆ•ธ้‡ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0322.Coin-Change/ https://leetcode.com/problems/coin-change/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0322.Coin-Change/Coin-Change.go package coinchange import ( \"math\" ) func min(a, b int) int { if a > b { return b } return a } var memo = map[int]int{} func dp(coins []int, n int) int { // ๆŸฅ่ฉขๅ‚™ๅฟ˜้Œ„ ้ฟๅ…้‡่ค‡ if _, vok := memo[n]; vok { return memo[n] } if n == 0 { return 0 } if n amount { return -1 } return dp[amount] } func CoinChange(coins []int, n int) int { var dpClosure func(n int) int dpClosure = func(n int) int { if n == 0 { return 0 } if n go test -benchmem -run=none LeetcodeGolang/Leetcode/0322.Coin-Change -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0322.Coin-Change cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz BenchmarkCoinChange-4 273376 4452 ns/op 0 B/op 0 allocs/op BenchmarkCoinChangeDP-4 11071686 128.1 ns/op 96 B/op 1 allocs/op BenchmarkCoinChangeMemoryTableRecursion-4 57663068 23.69 ns/op 0 B/op 0 allocs/op PASS ok LeetcodeGolang/Leetcode/0322.Coin-Change 4.194s amount = 11. k=[1,2,5] amount 0 1 2 3 4 5 ... 9 10 11 index 0 1 2 3 4 5 ... 9 10 11 dp 0 1 1 2 2 1 ... 3 2 3 dp[5] = 1+min(dp[5-1],dp[5-2],dp[5-5]) dp[11] = 1+min(dp[10],dp[9],dp[6]) ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0344.Reverse-String/":{"url":"Leetcode/0344.Reverse-String/","title":"0344.Reverse String","summary":null,"keywords":"","body":"344. Reverse String tagsstart Easy Two Pointers tagsstop ้กŒ็›ฎ Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters. Example 1: Input: [\"h\",\"e\",\"l\",\"l\",\"o\"] Output: [\"o\",\"l\",\"l\",\"e\",\"h\"] Example 2: Input: [\"H\",\"a\",\"n\",\"n\",\"a\",\"h\"] Output: [\"h\",\"a\",\"n\",\"n\",\"a\",\"H\"] ้กŒ็›ฎๅคงๆ„ ้กŒ็›ฎ่ฆๆฑ‚ๆˆ‘ๅ€‘ๅ่ฝ‰ไธ€ๅ€‹ๅญ—็ฌฆไธฒใ€‚ ่งฃ้กŒๆ€่ทฏ ้€™ไธ€้กŒ็š„่งฃ้กŒๆ€่ทฏๆ˜ฏ็”จ 2 ๅ€‹ๆŒ‡้‡๏ผŒๆŒ‡้‡ๅฐๆ’ž็š„ๆ€่ทฏ๏ผŒไพ†ไธๆ–ทไบคๆ›้ฆ–ๅฐพๅ…ƒ็ด ๏ผŒๅณๅฏใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0344.Reverse-String/ https://leetcode-cn.com/problems/reverse-string/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0344.Reverse-Stringm/Reverse-String.go package reversestring func ReverseString(s []byte) { for i, j := 0, len(s)-1; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0347.Top-K-Frequent-Elements/":{"url":"Leetcode/0347.Top-K-Frequent-Elements/","title":"347. Top K Frequent Elements","summary":"0347.Top-K-Frequent-Elements","keywords":"","body":"347. Top K Frequent Elements tagsstart LeetCode Go Medium Top K Frequent Elements heap tagsstop ้กŒ็›ฎ Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Constraints: 1 Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size. Seen this question in a real interview before? 1/4 Accepted 1.9M Submissions 3M Acceptance Rate 62.7% ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ๆ–นๆณ•ไธ€๏ผšheap ๆ–นๆณ•ไธ€๏ผšๅ † ๆ€่ทฏ่ˆ‡ๆผ”็ฎ—ๆณ• ้ฆ–ๅ…ˆ้ๆญทๆ•ดๅ€‹ๆ•ธ็ต„๏ผŒไธฆไฝฟ็”จๅ“ˆๅธŒ่กจ่จ˜้Œ„ๆฏๅ€‹ๆ•ธๅญ—ๅ‡บ็พ็š„ๆฌกๆ•ธ๏ผŒไธฆๅฝขๆˆไธ€ๅ€‹ใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€ใ€‚ ๆ‰พๅ‡บๅŽŸๆ•ธ็ต„็š„ๅ‰ k ๅ€‹้ซ˜้ ปๅ…ƒ็ด ๏ผŒๅฐฑ็ญ‰ๆ–ผๆ‰พๅ‡บใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€็š„ๅ‰ k ๅคง็š„ๅ€ผใ€‚ ๆœ€็ฐกๅ–ฎ็š„ๅšๆณ•ๆ˜ฏ็‚บใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€ๆŽ’ๅบใ€‚ ไฝ†็”ฑๆ–ผๅฏ่ƒฝๆœ‰O(N) ๅ€‹ไธๅŒ็š„ๅ‡บ็พๆฌกๆ•ธ๏ผˆๅ…ถไธญN ็‚บๅŽŸๆ•ธ็ต„้•ทๅบฆ๏ผ‰๏ผŒๆ•…็ธฝ็š„ๆผ”็ฎ—ๆณ•่ค‡้›œๅบฆๆœƒ้”ๅˆฐO(NlogโกN)๏ผŒไธ็ฌฆๅˆ้กŒ็›ฎ็š„่ฆๆฑ‚ใ€‚ ๅœจ้€™่ฃก๏ผŒๆˆ‘ๅ€‘ๅฏไปฅๅˆฉ็”จๅ †็š„ๆƒณๆณ•๏ผšๅปบ็ซ‹ไธ€ๅ€‹ๅฐ้ ‚ๅ †๏ผŒ็„ถๅพŒ้ๆญทใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€๏ผš ๅฆ‚ๆžœๅ †็š„ๅ…ƒ็ด ๅ€‹ๆ•ธๅฐๆ–ผ k๏ผŒๅฐฑๅฏไปฅ็›ดๆŽฅๆ’ๅ…ฅๅ †ไธญใ€‚ ๅฆ‚ๆžœๅ †็š„ๅ…ƒ็ด ๅ€‹ๆ•ธ็ญ‰ๆ–ผ k๏ผŒๅ‰‡ๆชขๆŸฅๅ †้ ‚่ˆ‡็›ฎๅ‰ๅ‡บ็พๆฌกๆ•ธ็š„ๅคงๅฐใ€‚ ๅฆ‚ๆžœๅ †้ ‚่ผƒๅคง๏ผŒ่กจ็คบ่‡ณๅฐ‘ๆœ‰ k ๅ€‹ๆ•ธๅญ—็š„ๅ‡บ็พๆฌกๆ•ธๆฏ”็›ฎๅ‰ๅ€ผๅคง๏ผŒๆ•…ๆจๆฃ„็›ฎๅ‰ๅ€ผ๏ผ›ๅฆๅ‰‡๏ผŒๅฐฑๅฝˆๅ‡บๅ †้ ‚๏ผŒไธฆๅฐ‡็›ฎๅ‰ๅ€ผๆ’ๅ…ฅๅ †ไธญใ€‚ ้ๆญทๅฎŒๆˆๅพŒ๏ผŒๅ †ไธญ็š„ๅ…ƒ็ด ๅฐฑไปฃ่กจไบ†ใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€ไธญๅ‰ k ๅคง็š„ๅ€ผใ€‚ ่ค‡้›œๅบฆๅˆ†ๆž ๆ™‚้–“่ค‡้›œๅบฆ๏ผšO(Nlogโกk)๏ผŒ ๅ…ถไธญ N ็‚บ้™ฃๅˆ—็š„้•ทๅบฆใ€‚ ๆˆ‘ๅ€‘ๅ…ˆ้ๆญทๅŽŸๆ•ธ็ต„๏ผŒไธฆไฝฟ็”จ้›œๆนŠ่กจ่จ˜้Œ„ๅ‡บ็พๆฌกๆ•ธ๏ผŒๆฏๅ€‹ๅ…ƒ็ด ้œ€่ฆO(1) ็š„ๆ™‚้–“๏ผŒๅ…ฑ้œ€O(N) ็š„ๆ™‚้–“ ใ€‚ ้šจๅพŒ๏ผŒๆˆ‘ๅ€‘้ๆญทใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€๏ผŒ็”ฑๆ–ผๅ †็š„ๅคงๅฐ่‡ณๅคš็‚บk๏ผŒๅ› ๆญคๆฏๆฌกๅ †ๆ“ไฝœ้œ€่ฆO(logโกk)็š„ๆ™‚้–“๏ผŒๅ…ฑ้œ€O(Nlogโกk)็š„ๆ™‚้–“ใ€‚ ไบŒ่€…ไน‹ๅ’Œ็‚บ O(Nlogโกk)ใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ๏ผšO(N)ใ€‚ ้›œๆนŠ่กจ็š„ๅคงๅฐ็‚บO(N)๏ผŒ่€Œๅ †็š„ๅคงๅฐ็‚บO(k)๏ผŒๅ…ฑ็‚บO(N)ใ€‚ ๆ–นๆณ•ไบŒ๏ผš Quick Sort Name Best Average Worst Memory Stable Quick sort n log(n) n log(n) n^2 log(n) No ไฝฟ็”จๅŸบๆ–ผๅฟซ้€ŸๆŽ’ๅบ็š„ๆ–นๆณ•๏ผŒๆฑ‚ๅ‡บใ€Œๅ‡บ็พๆฌกๆ•ธ้™ฃๅˆ—ใ€็š„ๅ‰ k ๅคง็š„ๅ€ผใ€‚ Big O ๆ–นๆณ•ไธ€๏ผšheap ๆ™‚้–“่ค‡้›œ : O(Nlogโกk) ็ฉบ้–“่ค‡้›œ : O(N) ๆ–นๆณ•ไบŒ๏ผš Quick Sort ๆ™‚้–“่ค‡้›œ : ็ฉบ้–“่ค‡้›œ : ไพ†ๆบ https://leetcode.com/problems/top-k-frequent-elements/description/ https://leetcode.cn/problems/top-k-frequent-elements/description/ https://books.halfrost.com/leetcode/ChapterFour/0300~0399/0347.Top-K-Frequent-Elements/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0347.Top-K-Frequent-Elements/main.go package topkfrequentelements import ( \"container/heap\" \"sort\" ) // ๆ–นๆณ•ไธ€: ไฝฟ็”จ PriorityQueue // ๆ™‚้–“่ค‡้›œ O(Nlogโกk), ็ฉบ้–“่ค‡้›œ O(N) // ้ฆ–ๅ…ˆ้ๆญทๆ•ดๅ€‹ๆ•ธ็ต„๏ผŒไธฆไฝฟ็”จๅ“ˆๅธŒ่กจ่จ˜้Œ„ๆฏๅ€‹ๆ•ธๅญ—ๅ‡บ็พ็š„ๆฌกๆ•ธ๏ผŒไธฆๅฝขๆˆไธ€ๅ€‹ใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€ // ๅปบ็ซ‹ไธ€ๅ€‹ PriortyQueue, ๅฐ‡ใ€Œๅ‡บ็พๆฌกๆ•ธๆ•ธ็ต„ใ€ไธŸ้€ฒๅŽป // ๅœจๆŠŠ PriortyQueue pop็š„ๅ€ผไธŸๅˆฐ result func TopKFrequent(nums []int, k int) []int { m := make(map[int]int) for i := 0; i pq[j].count } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] } func (pg *PriorityQueue) Push(v interface{}) { item := v.(*Item) *pg = append(*pg, item) } func (pg *PriorityQueue) Pop() interface{} { n := len(*pg) item := (*pg)[n-1] *pg = (*pg)[:n-1] return item } func (pg *PriorityQueue) PushPQ(v *Item) { heap.Push(pg, v) } func (pg *PriorityQueue) PopPQ() *Item { return heap.Pop(pg).(*Item) } // ๆ–นๆณ•ไบŒ: ไฝฟ็”จ Quick Sort // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() func TopKFrequentQuickSort(nums []int, k int) []int { m := make(map[int]int) for i := 0; i s[j][1] } func (s sortValue) Swap(i, j int) { s[i], s[j] = s[j], s[i] } Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkTopKFrequent-8 1875834 648.6 ns/op 200 B/op 11 allocs/op BenchmarkTopKFrequentQuickSort-8 1830498 704.2 ns/op 312 B/op 11 allocs/op PASS ok LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements 3.831s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0354.Russian-Doll-Envelopes/":{"url":"Leetcode/0354.Russian-Doll-Envelopes/","title":"0354. Russian Doll Envelope","summary":null,"keywords":"","body":"354. Russian Doll Envelope tagsstart Hard Dynamic Programming Binary Search tagsstop ้กŒ็›ฎ You are given a 2D array of integers envelopes where envelopes[i] = [wi, hi] represents the width and the height of an envelope. One envelope can fit into another if and only if both the width and height of one envelope are greater than the other envelope's width and height. Return the maximum number of envelopes you can Russian doll (i.e., put one inside the other). Note: You cannot rotate an envelope. Example 1: Input: envelopes = [[5,4],[6,4],[6,7],[2,3]] Output: 3 Explanation: The maximum number of envelopes you can Russian doll is 3 ([2,3] => [5,4] => [6,7]). Example 2: Input: envelopes = [[1,1],[1,1],[1,1]] Output: 1 Constraints: 1 envelopes[i].length == 2 1 ้กŒ็›ฎๅคงๆ„ ็ตฆไธ€ไบ›ไฟกๅฐ, ๆฏๅ€‹ไฟกๅฐ็”จๅฏฌๅบฆๅ’Œ้ซ˜ๅบฆ็š„ๆ•ดๆ•ธๅฐๅฝขๅผ(w,h)่กจ็คบ, ็•ถไธ€ๅ€‹ไฟกๅฐA็š„ๅฏฌๅบฆๅ’Œ้ซ˜ๅบฆ้ƒฝๆฏ”ๅฆไธ€ๅ€‹ไฟกๅฐBๅคง็š„ๆ™‚ๅ€™, ๅ‰‡Bๅฐฑๅฏไปฅๆ”พ้€ฒA่ฃก. ่จˆ็ฎ—ๅ‡บๆœ€ๅคšๆœ‰ๅคšๅฐ‘ไฟกๅฐ่ƒฝ็ต„ๆˆไธ€็ต„ ่งฃ้กŒๆ€่ทฏ ๅ…ˆๅฐๅฏฌๅบฆw้€ฒ่กŒๅ‡ๅบๆŽ’ๅบ, ๅฆ‚ๆžœ้‡ๅˆฐw็›ธๅŒ็š„ๆƒ…ๆณ, ๅ‰‡ๆŒ‰็…ง้ซ˜ๅบฆ้€ฒ่กŒ้™ๅบๆŽ’ๅบ. ไน‹ๅพŒๆŠŠๆ‰€ๆœ‰็š„hๆœ€็‚บไธ€ๅ€‹array, ๅฐๆญคarrayๅš ๆœ€้•ท้žๅขžๅญๅบๅˆ—(Longest Increasing Subsequence, LIS)็š„้•ทๅบฆๅฐฑๆ˜ฏ็ญ”ๆกˆ ๆญค้กŒๆ˜ฏไบŒ็ถญ็š„LISๅ•้กŒ, ไธ€็ถญLISๅƒ่€ƒ https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0300.Longest-Increasing-Subsequence/main.go ไธ‰็ถญ Leetcode No.1691 ไพ†ๆบ https://leetcode.com/problems/russian-doll-envelopes/ https://leetcode-cn.com/problems/russian-doll-envelopes/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0354.Russian-Doll-Envelopes/main.go package russiandollenvelopes import ( longestincreasingsubsequence \"LeetcodeGolang/Leetcode/0300.Longest-Increasing-Subsequence\" \"sort\" ) type sortEnvelopes [][]int func (s sortEnvelopes) Len() int { return len(s) } func (s sortEnvelopes) Less(i, j int) bool { if s[i][0] == s[j][0] { // ้‡ๅˆฐw็›ธๅŒ็š„ๆƒ…ๆณ, ๅ‰‡ๆŒ‰็…ง้ซ˜ๅบฆ้€ฒ่กŒ้™ๅบๆŽ’ๅบ return s[i][1] > s[j][1] } // ๅฐๅฏฌๅบฆw้€ฒ่กŒๅ‡ๅบๆŽ’ๅบ return s[i][0] e[1] { // ็พๅœจ็š„็‰Œๆฏ”ๅ †ๅฐ, ๆ‰€ๅฐ็ฏ„ๅœ right = mid } else if dp[mid] go test -benchmem -run=none LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes -bench=. goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkMaxEnvelopes-8 9067520 167.0 ns/op 88 B/op 3 allocs/op BenchmarkMaxEnvelopes2-8 6726646 214.9 ns/op 80 B/op 4 allocs/op PASS ok LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes 6.237s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0380.Insert-Delete-GetRandom-O1/":{"url":"Leetcode/0380.Insert-Delete-GetRandom-O1/","title":"380. Insert Delete GetRandom O(1)","summary":"0380.Insert-Delete-GetRandom-O(1)","keywords":"","body":"380. Insert Delete GetRandom O(1) tagsstart LeetCode Go Medium Insert Delete GetRandom O(1) Array Hash tagsstop ้กŒ็›ฎ Implement the RandomizedSet class: RandomizedSet() Initializes the RandomizedSet object. bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. You must implement the functions of the class such that each function works in average O(1) time complexity. Example 1: Input [\"RandomizedSet\", \"insert\", \"remove\", \"insert\", \"getRandom\", \"remove\", \"insert\", \"getRandom\"] [[], [1], [2], [2], [], [1], [2], []] Output [null, true, false, true, 2, true, false, 2] Explanation RandomizedSet randomizedSet = new RandomizedSet(); randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. randomizedSet.remove(2); // Returns false as 2 does not exist in the set. randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. randomizedSet.insert(2); // 2 was already in the set, so return false. randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. Constraints: -231 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ็”จmap็ด€้Œ„ๆฏๅ€‹ๅ…ƒ็ด ็š„index Big O ๆ™‚้–“่ค‡้›œ : O(1) ็ฉบ้–“่ค‡้›œ : O(n) ไพ†ๆบ https://leetcode.com/problems/insert-delete-getrandom-o1/description/ https://leetcode.cn/problems/insert-delete-getrandom-o1/description/ https://www.youtube.com/watch?v=46dZH7LDbf8 ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0380.Insert-Delete-GetRandom-O1/main.go package insertdeletegetrandom import \"math/rand\" // ๆ™‚้–“่ค‡้›œ O(1), ็ฉบ้–“่ค‡้›œ O(n) type RandomizedSet struct { arr []int set map[int]int size int } func Constructor() RandomizedSet { arr := make([]int, 0) set := make(map[int]int) size := 0 return RandomizedSet{arr, set, size} } func (this *RandomizedSet) Insert(val int) bool { if _, ok := this.set[val]; ok { return false } this.set[val] = this.size this.size++ this.arr = append(this.arr, val) return true } func (this *RandomizedSet) Remove(val int) bool { index, ok := this.set[val] if !ok { return false } // swapping lastValue := this.arr[this.size-1] this.arr[index] = lastValue this.set[lastValue] = index // Remove last value this.arr = this.arr[:this.size-1] delete(this.set, val) this.size-- return true } func (this *RandomizedSet) GetRandom() int { index := rand.Intn(this.size) return this.arr[index] } /** * Your RandomizedSet object will be instantiated and called as such: * obj := Constructor(); * param_1 := obj.Insert(val); * param_2 := obj.Remove(val); * param_3 := obj.GetRandom(); */ Benchmark Follow up ๅฆ‚ๆžœๅ…่จฑ้‡่ค‡, ่ญฌๅฆ‚ๅคšๅ€‹1 0381.Insert-Delete-GetRandom-O1-Duplicates-allowed #Hard ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/":{"url":"Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/","title":"381.Insert Delete GetRandom O(1) Duplicates allowed","summary":"0381.Insert-Delete-GetRandom-O1-Duplicates-allowed","keywords":"","body":"381.Insert Delete GetRandom O(1) Duplicates allowed tagsstart LeetCode Go Hard Insert Delete GetRandom O(1) Duplicates allowed Array Hash tagsstop ้กŒ็›ฎ ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element. Implement the RandomizedCollection class: RandomizedCollection() Initializes the empty RandomizedCollection object. bool insert(int val) Inserts an item val into the multiset, even if the item is already present. Returns true if the item is not present, false otherwise. bool remove(int val) Removes an item val from the multiset if present. Returns true if the item is present, false otherwise. Note that if val has multiple occurrences in the multiset, we only remove one of them. int getRandom() Returns a random element from the current multiset of elements. The probability of each element being returned is linearly related to the number of the same values the multiset contains. You must implement the functions of the class such that each function works on average O(1) time complexity. Note: The test cases are generated such that getRandom will only be called if there is at least one item in the RandomizedCollection. Example 1: Input [\"RandomizedCollection\", \"insert\", \"insert\", \"insert\", \"getRandom\", \"remove\", \"getRandom\"] [[], [1], [1], [2], [], [1], []] Output [null, true, false, true, 2, true, 1] Explanation RandomizedCollection randomizedCollection = new RandomizedCollection(); randomizedCollection.insert(1); // return true since the collection does not contain 1. // Inserts 1 into the collection. randomizedCollection.insert(1); // return false since the collection contains 1. // Inserts another 1 into the collection. Collection now contains [1,1]. randomizedCollection.insert(2); // return true since the collection does not contain 2. // Inserts 2 into the collection. Collection now contains [1,1,2]. randomizedCollection.getRandom(); // getRandom should: // - return 1 with probability 2/3, or // - return 2 with probability 1/3. randomizedCollection.remove(1); // return true since the collection contains 1. // Removes 1 from the collection. Collection now contains [1,2]. randomizedCollection.getRandom(); // getRandom should return 1 or 2, both equally likely. Constraints: -231 Big O ๆ™‚้–“่ค‡้›œ : O(1) ็ฉบ้–“่ค‡้›œ : O(n) ไพ†ๆบ https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/description/ https://leetcode.cn/problems/insert-delete-getrandom-o1-duplicates-allowed/description/ https://www.youtube.com/watch?v=46dZH7LDbf8 ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/main.go package insertdeletegetrandomo1duplicatesallowed import ( \"math/rand\" ) // ๆ™‚้–“่ค‡้›œ O(1), ็ฉบ้–“่ค‡้›œ O(n) type RandomizedCollection struct { arr []int set map[int]map[int]struct{} size int } func Constructor() RandomizedCollection { arr := make([]int, 0) set := make(map[int]map[int]struct{}) size := 0 return RandomizedCollection{arr, set, size} } func (this *RandomizedCollection) Insert(val int) bool { ids, ok := this.set[val] if !ok { // ๆฒ’ๆœ‰ๆญคๆ•ธๅญ—ไบ†, ๅปบ็ซ‹ไธ€ๅ€‹index็š„map ids = map[int]struct{}{} this.set[val] = ids } // index็š„map, key็‚บ็•ถๅ‰ๆœ€ๅพŒ็š„index, value็‚บ็ฉบ็š„struct{}{} ids[this.size] = struct{}{} this.arr = append(this.arr, val) this.size++ return !ok } func (this *RandomizedCollection) Remove(val int) bool { ids, ok := this.set[val] if !ok { return false } // ๆ‰พๅ‡บๆญคval็š„็š„index, ไธฆไธ”ๆŠŠๆœ€ๅพŒไธ€ๅ€‹index็š„mapๅˆช้™ค, ไธฆไธ”ๆŠŠๆญคindex็š„value่จญ็‚บ็ฉบ็š„struct{}{} var i int for id := range ids { i = id break } // ๅฐ‡ๆœ€ๅพŒไธ€็ญ†็งปๅˆฐ่ฆๆ›ฟๆ›็š„id this.arr[i] = this.arr[this.size-1] delete(ids, i) // ๅ› ็‚บๆŠŠๆœ€ๅพŒไธ€ๅ€‹ๅ…ƒ็ด ็งปๅˆฐๅ‰้ขไบ† delete(this.set[this.arr[i]], this.size-1) if i Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0409.Longest-Palindrome/":{"url":"Leetcode/0409.Longest-Palindrome/","title":"0409. Longest Palindrome","summary":null,"keywords":"","body":"409. Longest Palindrome tagsstart Easy String tagsstop ้กŒ็›ฎ Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive, for example, \"Aa\" is not considered a palindrome here. Example 1: Input: s = \"abccccdd\" Output: 7 Explanation: One longest palindrome that can be built is \"dccaccd\", whose length is 7. Example 2: Input: s = \"a\" Output: 1 Explanation: The longest palindrome that can be built is \"a\", whose length is 1. Constraints: 1 s consists of lowercase and/or uppercase English letters only. ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๅŒ…ๅซๅคงๅฏซๅญ—ๆฏๅ’Œๅฐๅฏซๅญ—ๆฏ็š„ๅญ—็ฌฆไธฒ๏ผŒๆ‰พๅˆฐ้€š้Ž้€™ไบ›ๅญ—ๆฏๆง‹้€ ๆˆ็š„ๆœ€้•ท็š„ๅ›žๆ–‡ไธฒใ€‚ ๅœจๆง‹้€ ้Ž็จ‹ไธญ๏ผŒ่ซ‹ๆณจๆ„ๅ€ๅˆ†ๅคงๅฐๅฏซใ€‚ๆฏ”ๅฆ‚ Aa ไธ่ƒฝ็•ถๅšไธ€ๅ€‹ๅ›žๆ–‡ๅญ—็ฌฆไธฒใ€‚ ๆณจๆ„:ๅ‡่จญๅญ—็ฌฆไธฒ็š„้•ทๅบฆไธๆœƒ่ถ…้Ž 1010ใ€‚ ่งฃ้กŒๆ€่ทฏ ็ตฆๅ‡บไธ€ๅ€‹ๅญ—็ฌฆไธฒ๏ผŒ่ฆๆฑ‚็”จ้€™ๅ€‹ๅญ—็ฌฆไธฒ่ฃก้ข็š„ๅญ—็ฌฆ็ต„ๆˆไธ€ๅ€‹ๅ›žๆ–‡ไธฒ๏ผŒๅ•ๅ›žๆ–‡ไธฒๆœ€ๅคšๅฏไปฅ็ต„ๅˆๆˆๅคš้•ท็š„๏ผŸ ้€™ไนŸๆ˜ฏไธ€้“้กŒๆฐด้กŒ๏ผŒ็„ถๅพŒๅ…ˆ็ตฑ่จˆๆฏๅ€‹ๅญ—็ฌฆ็š„้ ปๆฌก๏ผŒๆฏๅ€‹ๅญ—็ฌฆ่ƒฝๅ–2ๅ€‹็š„ๅ–2ๅ€‹๏ผŒไธ่ถณ2ๅ€‹็š„ไธฆไธ”็•ถๅ‰ๆง‹้€ ไธญ็š„ๅ›žๆ–‡ไธฒๆ˜ฏๅถๆ•ธ็š„ๆƒ…ๆณไธ‹๏ผˆๅณๆฏ2ๅ€‹้ƒฝ้™ฃๅฎนไบ†๏ผ‰๏ผŒๅฏไปฅๅ–1ๅ€‹ใ€‚ๆœ€ๅพŒ็ต„ๅˆๅ‡บไพ†็š„ๅฐฑๆ˜ฏ็ต‚ๆญขๅ›žๆ–‡ไธฒใ€‚ ไพ†ๆบ https://leetcode.com/problems/longest-palindrome/ ่งฃ็ญ” package longestpalindrome func LongestPalindrome(s string) int { counter := make(map[rune]int) for _, r := range s { counter[r]++ } result := 0 for _, v := range counter { result += v / 2 * 2 // ๅญ—็ฌฆๅ‡บ็พๅฅ‡ๆ•ธๆฌก๏ผŒๆˆ‘ๅ€‘ๅฏไปฅ้ธๆ“‡ๅ…ถไธญไธ€ๅ€‹, ๆ”พๅœจๅ›žๆ–‡ไธฒ็š„ไธญ้–“๏ผŒ้€™ๅฏไปฅ่ฒข็ปไธ€ๅ€‹้•ทๅบฆ if result%2 == 0 && v%2 == 1 { result++ } } return result } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0412.Fizz-Buzz/":{"url":"Leetcode/0412.Fizz-Buzz/","title":"412. Fizz Buzz","summary":"0412.Fizz-Buzz","keywords":"","body":"412. Fizz Buzz tagsstart LeetCode Go Easy Fizz Buzz Facebook Microsoft Apple string math tagsstop ้กŒ็›ฎ Facebook, Microsoft, Apple Given an integer n, return a string array answer (1-indexed) where: answer[i] == \"FizzBuzz\" if i is divisible by 3 and 5. answer[i] == \"Fizz\" if i is divisible by 3. answer[i] == \"Buzz\" if i is divisible by 5. answer[i] == i (as a string) if none of the above conditions are true. Example 1: Input: n = 3 Output: [\"1\",\"2\",\"Fizz\"] Example 2: Input: n = 5 Output: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\"] Example 3: Input: n = 15 Output: [\"1\",\"2\",\"Fizz\",\"4\",\"Buzz\",\"Fizz\",\"7\",\"8\",\"Fizz\",\"Buzz\",\"11\",\"Fizz\",\"13\",\"14\",\"FizzBuzz\"] Constraints: 1 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : O(n) ไพ†ๆบ https://leetcode.com/problems/fizz-buzz/description/ https://leetcode.cn/problems/fizz-buzz/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0412.Fizz-Buzz/main.go package fizzbuzz import \"strconv\" // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() func fizzBuzz(n int) []string { var result []string for i := 1; i Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0412.Fizz-Buzz cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz BenchmarkFizzBuzz-4 5918809 287.1 ns/op 112 B/op 3 allocs/op BenchmarkFizzBuzz2-4 5024536 223.8 ns/op 112 B/op 3 allocs/op BenchmarkFizzBuzz3-4 5406643 196.3 ns/op 112 B/op 3 allocs/op PASS ok LeetcodeGolang/Leetcode/0412.Fizz-Buzz 5.507s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0438.Find-All-Anagrams-in-a-String/":{"url":"Leetcode/0438.Find-All-Anagrams-in-a-String/","title":"0438.Find All Anagrams in a String","summary":null,"keywords":"","body":"438. Find All Anagrams in a String tagsstart Medium Sliding Window tagsstop ้ข˜็›ฎ Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Input: s = \"cbaebabacd\", p = \"abc\" Output: [0,6] Explanation: The substring with start index = 0 is \"cba\", which is an anagram of \"abc\". The substring with start index = 6 is \"bac\", which is an anagram of \"abc\". Example 2: Input: s = \"abab\", p = \"ab\" Output: [0,1,2] Explanation: The substring with start index = 0 is \"ab\", which is an anagram of \"ab\". The substring with start index = 1 is \"ba\", which is an anagram of \"ab\". The substring with start index = 2 is \"ab\", which is an anagram of \"ab\". Constraints: 1 ้กŒ็›ฎๅคงๆ„ ๆ‰พๆ‰€ๆœ‰ๅญ—ๆฏ็•ฐไฝ่ฉž, ๅฐฑๅƒๅ…จๆŽ’ๅˆ— ็ตฆๅฎšไธ€ๅ€‹ๅญ—็ฌฆไธฒ S ๅ’Œ้ž็ฉบ็š„ๅญ—็ฌฆไธฒ P, ๆ‰พๅˆฐ S ไธญๆ‰€ๆœ‰ๆ˜ฏ P ๅพ—ๆŽ’ๅˆ—, ไธฆ่ฟ”ๅ›žไป–็š„่ตทๅง‹ index ่งฃ้กŒๆ€่ทฏ ่ทŸ 0567.Permutation-in-String้กžไผผ, ๅชๆ˜ฏๆŠŠๆ‰พๅˆฐ็š„็ญ”ๆกˆ่จ˜้Œ„่ตทไพ† ไพ†ๆบ https://leetcode.com/problems/find-all-anagrams-in-a-string/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0438.Find-All-Anagrams-in-a-String/main.go package findallanagramsinastring func FindAnagrams(s string, p string) []int { need, window := make(map[rune]int), make(map[rune]int) for _, c := range p { need[c]++ } left, right := 0, 0 valid := 0 res := []int{} //็ด€้Œ„็ตๆžœ for right 0 { window[c]++ if window[c] == need[c] { valid++ } } // fmt.Printf(\"[%d,%d) \\n\", left, right) // ๅˆคๆ–ทๅทฆ่ฆ–็ช—ๆ˜ฏๅฆๆ”ถ็ธฎ, ็œ‹็œ‹่ฆ–็ช—้•ทๅบฆๆ˜ฏๅฆๅŒ่ฆๆ‰พ็š„ๅญ—ไธฒ็š„้•ทๅบฆ if (right - left) >= len(p) { if valid == len(need) { // ๆƒณ่ฆ็š„ๅญ—ๅ…ƒ้ƒฝๆ‰พๅˆฐไบ†, ็ด€้Œ„index res = append(res, left) } d := rune(s[left]) left++ if need[d] > 0 { if window[d] == need[d] { valid-- } window[d]-- } } } return res } // ็”จ slice ๅ–ไปฃ map ไพ†ๅ„ชๅŒ– func FindAnagramsSlice(s string, p string) []int { need := [256]int{} for _, c := range p { need[c-'a']++ } left, right := 0, 0 count := len(p) res := []int{} for right 0 { count-- } need[c]-- right++ if count == 0 { res = append(res, left) } if (right - left) >= len(p) { d := s[left] - 'a' if need[d] >= 0 { count++ } need[d]++ left++ } } return res } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0509.Fibonacci-Number/":{"url":"Leetcode/0509.Fibonacci-Number/","title":"0509.Fibonacci Number","summary":null,"keywords":"","body":"509. Fibonacci Number tagsstart Easy Dynamic Programming tagsstop ้กŒ็›ฎ The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is, F(0) = 0, F(1) = 1 F(n) = F(n - 1) + F(n - 2), for n > 1. Given n, calculate F(n). Example 1: Input: n = 2 Output: 1 Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. Example 2: Input: n = 3 Output: 2 Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. Example 3: Input: n = 4 Output: 3 Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. Constraints: 0 ้กŒ็›ฎๅคงๆ„ ๆ–ๆณข้‚ฃๅฅ‘ๆ•ธๅˆ—, ้€šๅธธ็”จ F(n) ่กจ็คบ F(0) = 0, F(1) = 1 F(N) = F(N - 1) + F(N - 2), ๅ…ถไธญ N > 1. ็ตฆๅฎš N๏ผŒ่จˆ็ฎ— F(N)ใ€‚ ๆ็คบ๏ผš0 โ‰ค N โ‰ค 30 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 ,610, 987โ€ฆโ€ฆ ่งฃ้กŒๆ€่ทฏ ้‡ๅˆฐ้ž่ฟดๆœ€ๅฅฝ็•ซๅ‡บ้ž่ฟดๆจน f(20) / \\ f(19) f(18) ... ... / \\ / \\ f(1) f(2) f(1) f(2) ้€™ไธ€้กŒ่งฃๆณ•ๅพˆๅคš๏ผŒๅคง็š„ๅˆ†้กžๆ˜ฏๅ››็จฎ๏ผŒ้žๆญธ๏ผŒ่จ˜ๆ†ถๅŒ–ๆœ็ดข(dp)๏ผŒ็Ÿฉ้™ฃๅฟซ้€Ÿๅ†ช๏ผŒ้€š้ …ๅ…ฌๅผใ€‚ๅ…ถไธญ่จ˜ๆ†ถๅŒ–ๆœ็ดขๅฏไปฅๅฏซ 3 ็จฎๆ–นๆณ•๏ผŒ่‡ชๅบ•ๅ‘ไธŠ็š„๏ผŒ่‡ช้ ‚ๅ‘ไธ‹็š„๏ผŒๅ„ชๅŒ–็ฉบ้–“่ค‡้›œๅบฆ็‰ˆ็š„ใ€‚้€š้ …ๅ…ฌๅผๆ–นๆณ•ๅฏฆ่ณชๆ˜ฏๆฑ‚ a^b ้€™ๅ€‹้‚„ๅฏไปฅ็”จๅฟซ้€Ÿๅ†ชๅ„ชๅŒ–ๆ™‚้–“่ค‡้›œๅบฆๅˆฐ O(log n) ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0500~0599/0509.Fibonacci-Number/ https://leetcode.com/problems/fibonacci-number/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0509.Fibonacci-Number/Fibonacci-Number.go // --- Directions // Print out the n-th entry in the fibonacci series. // The fibonacci series is an ordering of numbers where // each number is the sum of the preceeding two. // For example, the sequence // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] // forms the first ten entries of the fibonacci series. // Example: // fib(4) === 3 package fibonaccinumber import \"math\" // Fib : iterative ่ฟดๅœˆ O(n) . ็ฉบ้–“่ค‡้›œ O(n). ่‡ชๅบ•ๅ‘ไธŠ็š„่จ˜ๆ†ถๅŒ–ๆœ็ดข func FibIterative(n int) int { var result = []int{0, 1} for i := 2; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0516.Longest-Palindromic-Subsequence/":{"url":"Leetcode/0516.Longest-Palindromic-Subsequence/","title":"516. Longest Palindromic Subsequence","summary":null,"keywords":"","body":"516. Longest Palindromic Subsequence tagsstart Medium Dynamic Programming tagsstop ้กŒ็›ฎ Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: s = \"bbbab\" Output: 4 Explanation: One possible longest palindromic subsequence is \"bbbb\". Example 2: Input: s = \"cbbd\" Output: 2 Explanation: One possible longest palindromic subsequence is \"bb\". Constraints: 1 s consists only of lowercase English letters. ้กŒ็›ฎๅคงๆ„ ็ตฆไฝ ไธ€ๅ€‹ๅญ—็ฌฆไธฒ s๏ผŒๆ‰พๅˆฐ s ไธญๆœ€้•ท็š„ๅ›žๆ–‡ๅญไธฒใ€‚ ่งฃ้กŒๆ€่ทฏ ไพ†ๆบ https://leetcode.com/problems/longest-palindromic-subsequence/ ่งฃ็ญ” ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0543.Diameter-of-Binary-Tree/":{"url":"Leetcode/0543.Diameter-of-Binary-Tree/","title":"0543. Diameter of Binary Tree","summary":"0543.Diameter-of-Binary-Tree","keywords":"","body":"543. Diameter of Binary Tree tagsstart LeetCode Go Easy Diameter of Binary Tree DFS tagsstop ้กŒ็›ฎ Given the root of a binary tree, return the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root. The length of a path between two nodes is represented by the number of edges between them. Example 1: Input: root = [1,2,3,4,5] Output: 3 Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3]. Example 2: Input: root = [1,2] Output: 1 Constraints: The number of nodes in the tree is in the range [1, 104]. -100 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ ๅทฆ้‚Š็š„ๆœ€้ซ˜้ซ˜ๅบฆ่ˆ‡ๅณ้‚Š็š„ๆœ€้ซ˜้ซ˜ๅบฆ็›ธๅŠ  Big O ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ: ๆœ€ๅฃž O(n), ๅนณ่กกๆจน O(log(n)) ไพ†ๆบ https://leetcode.com/problems/diameter-of-binary-tree/ https://leetcode.cn/problems/diameter-of-binary-tree/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0543.Diameter-of-Binary-Tree/main.go package diameterofbinarytree import \"LeetcodeGolang/structures\" /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ type TreeNode = structures.TreeNode var maxDiameter int // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ: ๆœ€ๅฃž O(n), ๅนณ่กกๆจน O(log(n)) func DiameterOfBinaryTree(root *TreeNode) int { if root == nil { return 0 } maxDiameter = 0 maxDepth(root) return maxDiameter } func maxDepth(node *TreeNode) int { if node == nil { return 0 } left := maxDepth(node.Left) right := maxDepth(node.Right) maxDiameter = max(maxDiameter, left+right) return max(left, right) + 1 } func max(a, b int) int { if a >= b { return a } else { return b } } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0567.Permutation-in-String/":{"url":"Leetcode/0567.Permutation-in-String/","title":"0567.Permutation in String","summary":null,"keywords":"","body":"567. Permutation in String tagsstart Medium Sliding Window tagsstop ้กŒ็›ฎ Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise. In other words, return true if one of s1's permutations is the substring of s2. Example 1: Input: s1 = \"ab\", s2 = \"eidbaooo\" Output: true Explanation: s2 contains one permutation of s1 (\"ba\"). Example 2: Input: s1 = \"ab\", s2 = \"eidboaoo\" Output: false Constraints: 1 s1 and s2 consist of lowercase English letters. ้กŒ็›ฎๅคงๆ„ ่ผธๅ…ฅๅ…ฉๅ€‹String S1 ๅ’Œ S2 , ๅˆคๆ–ท S2 ๆ˜ฏๅฆๅŒ…ๅซS1็š„ๆŽ’ๅˆ—, ไนŸๅฐฑๆ˜ฏ่ฆๅˆคๆ–ท S2 ไธญๆ˜ฏๅฆๅญ˜ๅœจไธ€ๅ€‹ๅญๅญ—ไธฒๆ˜ฏS1็š„ไธ€็จฎๅ…จๆŽ’ๅˆ— ่งฃ้กŒๆ€่ทฏ Sliding Window ๅฏไปฅ็”จ slice ๅ–ไปฃ map ไพ†ๅ„ชๅŒ– ไพ†ๆบ https://leetcode.com/problems/permutation-in-string/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0567.Permutation-in-String/main.go package permutationinstring func CheckInclusion(s1 string, s2 string) bool { need, window := make(map[rune]int), make(map[rune]int) for _, c := range s1 { need[c]++ } left, right := 0, 0 valid := 0 for right 0 { window[c]++ if window[c] == need[c] { // ่ฉฒๅญ—็ฌฆ้•ทๅบฆ้”ๅˆฐ valid++ } } // fmt.Printf(\"[%d,%d) \\n\", left, right) // ๅˆคๆ–ทๅทฆ่ฆ–็ช—ๆ˜ฏๅฆ่ฆๆ”ถ็ธฎ // for (right - left) >= len(s1) if (right - left) >= len(s1) { if valid == len(need) { // ๅ…จๆ‰พๅˆฐ return true } d := rune(s2[left]) left++ if need[d] > 0 { if window[d] == need[d] { valid-- } window[d]-- } } } return false } // ็”จ slice ๅ–ไปฃ map ไพ†ๅ„ชๅŒ– func CheckInclusionSlice(s1 string, s2 string) bool { need := [256]int{} for _, c := range s1 { need[c-'a']++ } left, right := 0, 0 count := len(s1) for right 0 { // ๆœ‰ๆ‰พๅˆฐ count-- } need[c]-- right++ // fmt.Printf(\"[%d,%d)\\n\", left, right) if count == 0 { return true } // ๅˆคๆ–ทๅทฆ่ฆ–็ช—ๆ˜ฏๅฆ่ฆๆ”ถ็ธฎ if (right - left) == len(s1) { d := s2[left] - 'a' if need[d] >= 0 { // ็ฌฆๅˆ้ ๆœŸ็š„้•ทๅบฆ, ไฝ†ๆ˜ฏๅปๆฒ’ๆ‰พๅˆฐ้ ๆœŸ็š„็ตๆžœ count++ } need[d]++ left++ } } return false } tags: Medium Leetcode Sliding Window ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0693.Binary-Number-with-Alternating-Bits/":{"url":"Leetcode/0693.Binary-Number-with-Alternating-Bits/","title":"0693.Binary Number with Alternating Bits","summary":null,"keywords":"","body":"693. Binary Number with Alternating Bits tagsstart Medium Bit Manipulation tagsstop ้กŒ็›ฎ Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values. Example 1: Input: 5 Output: True Explanation: The binary representation of 5 is: 101 Example 2: Input: 7 Output: False Explanation: The binary representation of 7 is: 111. Example 3: Input: 11 Output: False Explanation: The binary representation of 11 is: 1011. Example 4: Input: 10 Output: True Explanation: The binary representation of 10 is: 1010. ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๆญฃๆ•ดๆ•ธ๏ผŒๆชขๆŸฅไป–ๆ˜ฏๅฆ็‚บไบคๆ›ฟไฝไบŒ้€ฒๅˆถๆ•ธ๏ผšๆ›ๅฅ่ฉฑ่ชช๏ผŒๅฐฑๆ˜ฏไป–็š„ไบŒ้€ฒๅˆถๆ•ธ็›ธ้„ฐ็š„ๅ…ฉๅ€‹ไฝๆ•ธๆฐธไธ็›ธ็ญ‰ใ€‚ ่งฃ้กŒๆ€่ทฏ ๅˆคๆ–ทไธ€ๅ€‹ๆ•ธ็š„ไบŒ้€ฒๅˆถไฝ็›ธ้„ฐๅ…ฉๅ€‹ๆ•ธๆ˜ฏไธ็›ธ็ญ‰็š„๏ผŒๅณ 0101 ไบคๅ‰้–“้š”็š„๏ผŒๅฆ‚ๆžœๆ˜ฏ๏ผŒ่ผธๅ‡บ trueใ€‚้€™ไธ€้กŒๆœ‰ๅคš็จฎๅšๆณ•๏ผŒๆœ€็ฐกๅ–ฎ็š„ๆ–นๆณ•ๅฐฑๆ˜ฏ็›ดๆŽฅๆจกๆ“ฌใ€‚ๆฏ”่ผƒๅทงๅฆ™็š„ๆ–นๆณ•ๆ˜ฏ้€š้Žไฝ้‹็ฎ—๏ผŒๅˆ็†ๆง‹้€ ็‰นๆฎŠๆ•ธๆ“š้€ฒ่กŒไฝ้‹็ฎ—ๅˆฐ้”็›ฎ็š„ใ€‚ 010101 ๆง‹้€ ๅ‡บ 101010 ๅ…ฉ่€…็›ธไบ’ & ไฝ้‹็ฎ—ไปฅๅพŒๅฐฑ็‚บ 0๏ผŒๅ› ็‚บ้ƒฝโ€œๆ’็ฉบโ€ไบ†ใ€‚ ๆ็คบ๏ผš 1 ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0600~0699/0693.Binary-Number-with-Alternating-Bits/ https://leetcode-cn.com/problems/binary-number-with-alternating-bits/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0693.Binary-Number-with-Alternating-Bits/Binary-Number-with-Alternating-Bits.go package binarynumberwithalternatingbits // ๆšดๅŠ›่งฃ O(n) func hasAlternatingBits(n int) bool { for n > 0 { preBit := n & 1 n = n / 2 curBit := n & 1 if curBit == preBit { return false } } return true } // ๆ•ธๅญธ่งฃ func hasAlternatingBits2(n int) bool { /* n=5 n= 1 0 1 n >> 1 0 1 0 n^(n>>1) 1 1 1 (XOR ไธๅŒๆ™‚ๅพ—1) n 1 1 1 n+1 1 0 0 0 n & (n+1) 0 0 0 n=7 n= 1 1 1 n >> 1 0 1 1 n^(n>>1) 1 0 0 (XOR ไธๅŒๆ™‚ๅพ—1) n 1 0 0 n+1 1 0 1 n & (n+1) 1 0 0 */ n = n ^ (n >> 1) result := n & (n + 1) return result == 0 } ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0695.Max-Area-of-Island/":{"url":"Leetcode/0695.Max-Area-of-Island/","title":"0695.Max Area of Island","summary":"Max Area of Island","keywords":"","body":"695. Max Area of Island tagsstart LeetCode Go Medium Max Area of Island DFS BFS Array & String Matrix tagsstop ้กŒ็›ฎ You are given an m x n binary matrix grid. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. The area of an island is the number of cells with a value 1 in the island. Return the maximum area of an island in grid. If there is no island, return 0. Example 1: Input: grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]] Output: 6 Explanation: The answer is not 11, because the island must be connected 4-directionally. Example 2: Input: grid = [[0,0,0,0,0,0,0,0]] Output: 0 Constraints: m == grid.length n == grid[i].length 1 grid[i][j] is either 0 or 1. ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹็”ฑ '1'๏ผˆ้™ธๅœฐ๏ผ‰ๅ’Œ '0'๏ผˆๆฐดๅŸŸ๏ผ‰็ต„ๆˆ็š„ไบŒ็ถญ็Ÿฉ้™ฃ๏ผŒ่จˆ็ฎ—็Ÿฉ้™ฃไธญ้€ฃ็บŒ็š„1ๆ‰€็ต„ๆˆ็š„ๆœ€ๅคงๅ€ๅŸŸ็š„้ข็ฉใ€‚ ่งฃ้กŒๆ€่ทฏ ไฝฟ็”จBFSๆˆ–DFS้ๆญท็Ÿฉ้™ฃ๏ผŒ่จˆ็ฎ—ๆฏๅ€‹ๅณถๅถผ็š„้ข็ฉ๏ผŒไธฆๆ‰พๅˆฐๆœ€ๅคง็š„้ข็ฉๅ€ผใ€‚ ็ตฆๅ‡บไธ€ๅ€‹ๅœฐๅœ–๏ผŒ่ฆๆฑ‚่จˆ็ฎ—ไธŠ้ขๅณถๅถผ็š„ใ€‚ๆณจๆ„ๅณถๅถผ็š„ๅฎš็พฉๆ˜ฏ่ฆๆฑ‚้ƒฝๆ˜ฏๆตท๏ผˆ็‚บ0็š„้ปž๏ผ‰๏ผŒๅฆ‚ๆžœๅœŸๅœฐ๏ผˆ็‚บ1็š„้ปž๏ผ‰้ ๅœจๅœฐๅœ–้‚Š็ทฃ๏ผŒไธ่ƒฝๆ˜ฏ็Š็‘šๅณถใ€‚ ้€™้กŒๅ’Œ็ฌฌ200้กŒ๏ผŒ็ฌฌ1254้กŒ่งฃ้กŒๆ€่ทฏๆ˜ฏไธ€่‡ด็š„ใ€‚ DPSๆทฑๆœใ€‚ไธ้Ž้€™้กŒ้œ€่ฆๅคš่™•็†2ไปถไบ‹ๆƒ…๏ผŒไธ€ๆ˜ฏๆณจๆ„้ ้‚Š็ทฃ็š„ๅณถๅถผไธ่ƒฝ่จˆ็ฎ—้—œไฟ‚๏ผŒไบŒๆ˜ฏๅ‹•ๆ…‹็ถญ่ญทๅณถๅถผ็š„ๆœ€ๅคง้ข็ฉใ€‚ ไฝฟ็”จDFS็š„่งฃๆณ•๏ผš ๅ‰ตๅปบไธ€ๅ€‹่ฎŠ้‡maxArea๏ผŒ็”จๆ–ผ่จ˜้Œ„ๆœ€ๅคง้ข็ฉ๏ผŒๅˆๅง‹ๅŒ–็‚บ0ใ€‚ ้ๆญทไบŒ็ถญ็ถฒๆ ผ๏ผŒๅฐๆ–ผๆฏๅ€‹็‚บ1็š„ไฝ็ฝฎ๏ผŒ่ชฟ็”จdfsๅ‡ฝๆ•ธ่จˆ็ฎ—ไปฅ่ฉฒไฝ็ฝฎ็‚บ่ตท้ปž็š„ๅณถๅถผ้ข็ฉใ€‚ ๅœจdfsๅ‡ฝๆ•ธไธญ๏ผŒ้ฆ–ๅ…ˆๆชขๆŸฅ็•ถๅ‰ไฝ็ฝฎ็š„ๅˆๆณ•ๆ€ง๏ผŒๅฆ‚ๆžœ่ถ…ๅ‡บ็ถฒๆ ผ็ฏ„ๅœๆˆ–่€…่ฉฒไฝ็ฝฎๅทฒ็ถ“่จชๅ•้Žๆˆ–่€…ๆ˜ฏๆฐดๅŸŸ๏ผˆ0๏ผ‰๏ผŒๅ‰‡่ฟ”ๅ›ž0ใ€‚ ๅฐ‡็•ถๅ‰ไฝ็ฝฎๆจ™่จ˜็‚บๅทฒ่จชๅ•๏ผŒไธฆๅˆๅง‹ๅŒ–้ข็ฉ็‚บ1ใ€‚ ้ž่ฟดๅœฐๅฐ็•ถๅ‰ไฝ็ฝฎ็š„ไธŠใ€ไธ‹ใ€ๅทฆใ€ๅณๅ››ๅ€‹็›ธ้„ฐไฝ็ฝฎ้€ฒ่กŒdfs๏ผŒไธฆๅฐ‡่ฟ”ๅ›ž็š„้ข็ฉๅŠ ๅˆฐ็•ถๅ‰้ข็ฉไธŠใ€‚ ่ฟ”ๅ›ž็•ถๅ‰้ข็ฉใ€‚ ๆ›ดๆ–ฐmaxArea็‚บ็•ถๅ‰้ข็ฉๅ’ŒmaxAreaไธญ็š„่ผƒๅคงๅ€ผใ€‚ ้ๆญทๅฎŒๆ•ดๅ€‹็ถฒๆ ผๅพŒ๏ผŒ่ฟ”ๅ›žmaxAreaไฝœ็‚บ็ตๆžœใ€‚ ๆ™‚้–“่ค‡้›œๅบฆ: ้ๆญทๆ•ดๅ€‹็ถฒๆ ผ็š„ๆ™‚้–“่ค‡้›œๅบฆ็‚บO(mn)๏ผŒๅ…ถไธญmๅ’Œnๅˆ†ๅˆฅ็‚บ็ถฒๆ ผ็š„่กŒๆ•ธๅ’Œๅˆ—ๆ•ธใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ: ไฝฟ็”จไบ†้ž่ฟด่ชฟ็”จ็š„ๆ ˆ็ฉบ้–“๏ผŒ็ฉบ้–“่ค‡้›œๅบฆ็‚บO(mn)ใ€‚ ไพ†ๆบ https://leetcode.com/problems/max-area-of-island/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0695.Max-Area-of-Island/main.go package maxareaofisland var ( dir = [][]int{ {-1, 0}, // ไธŠ {0, 1}, // ๅณ {1, 0}, // ไธ‹ {0, -1}, // ๅทฆ } ) func MaxAreaOfIsland(grid [][]int) int { result := 0 for i, row := range grid { for j, col := range row { if col == 1 { result = max(result, areaOfIsland(grid, i, j)) } } } return result } // DFS func areaOfIsland(grid [][]int, x, y int) int { if x = len(grid) || y = len(grid[0]) || grid[x][y] == 0 { return 0 } // ่จญ็‚บ0๏ผŒ้ฟๅ…้‡่ค‡่จˆ็ฎ— grid[x][y] = 0 total := 1 // ๅ››ๅ€‹ๆ–นๅ‘ๆŸฅๆ‰พ for i := 0; i y { return x } return y } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0703.Kth-Largest-Element-in-a-Stream/":{"url":"Leetcode/0703.Kth-Largest-Element-in-a-Stream/","title":"0703. Kth Largest Element in a Stream","summary":"0703.Kth-Largest-Element-in-a-Stream","keywords":"","body":"0703. Kth Largest Element in a Stream tagsstart LeetCode Go Easy Kth Largest Element in a Stream Heap Priority Queue tagsstop ้กŒ็›ฎ Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class: KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream. Example 1: Input [\"KthLargest\", \"add\", \"add\", \"add\", \"add\", \"add\"] [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]] Output [null, 4, 5, 5, 8, 8] Explanation KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]); kthLargest.add(3); // return 4 kthLargest.add(5); // return 5 kthLargest.add(10); // return 5 kthLargest.add(9); // return 8 kthLargest.add(4); // return 8 Constraints: 1 ้กŒ็›ฎๅคงๆ„ ่จญ่จˆไธ€ๅ€‹ๆ‰พๅˆฐๆ•ธๆ“šๆตไธญ็ฌฌ k ๅคงๅ…ƒ็ด ็š„้กž๏ผˆclass๏ผ‰ใ€‚ ๆณจๆ„ๆ˜ฏๆŽ’ๅบๅพŒ็š„็ฌฌ k ๅคงๅ…ƒ็ด ๏ผŒไธๆ˜ฏ็ฌฌ k ๅ€‹ไธๅŒ็š„ๅ…ƒ็ด ใ€‚ ่ซ‹ๅฏฆ็พ KthLargest ้กž๏ผš KthLargest๏ผˆint k๏ผŒ int[] nums๏ผ‰ ไฝฟ็”จๆ•ดๆ•ธ k ๅ’Œๆ•ดๆ•ธๆต nums ๅˆๅง‹ๅŒ–็‰ฉไปถใ€‚ int add๏ผˆint val๏ผ‰ ๅฐ‡ val ๆ’ๅ…ฅๆ•ธๆ“šๆต nums ๅพŒ๏ผŒ่ฟ”ๅ›ž็•ถๅ‰ๆ•ธๆ“šๆตไธญ็ฌฌ k ๅคง็š„ๅ…ƒ็ด ใ€‚ ่งฃ้กŒๆ€่ทฏ ้€™้กŒ่€ƒๅฏŸๅ„ชๅ…ˆ้ †ๅบไฝ‡ๅˆ—็š„ไฝฟ็”จ๏ผŒๅฏไปฅๅ…ˆๅšไธ‹้€™้“้กžไผผ็š„้กŒ็›ฎ 215.้™ฃๅˆ—ไธญ็š„็ฌฌ K ๅ€‹ๆœ€ๅคงๅ…ƒ็ด ใ€‚ golang container/heap Big O ๆ™‚้–“่ค‡้›œ : ๅˆๅง‹ๅŒ–ๆ™‚้–“่ค‡้›œๅบฆ็‚บ๏ผš O(nlogโกk) ๏ผŒๅ…ถไธญ n ็‚บๅˆๅง‹ๅŒ–ๆ™‚ nums ็š„้•ทๅบฆ; ๅ–ฎๆฌกๆ’ๅ…ฅๆ™‚้–“่ค‡้›œๅบฆ็‚บ๏ผš O(logโกk) ็ฉบ้–“่ค‡้›œ : O(k)ใ€‚ ้œ€่ฆไฝฟ็”จๅ„ชๅ…ˆไฝ‡ๅˆ—ๅญ˜ๅ„ฒๅ‰ k ๅคง็š„ๅ…ƒ็ด  ไพ†ๆบ https://leetcode.com/problems/kth-largest-element-in-a-stream/ https://leetcode.cn/problems/kth-largest-element-in-a-stream/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0703.Kth-Largest-Element-in-a-Stream/main.go package kthlargestelementinastream import ( \"container/heap\" \"sort\" ) /** * Your KthLargest object will be instantiated and called as such: * obj := Constructor(k, nums); * param_1 := obj.Add(val); */ // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() type KthLargest struct { sort.IntSlice k int } func Constructor(k int, nums []int) KthLargest { kl := KthLargest{k: k} for _, val := range nums { kl.Add(val) } return kl } func (kl *KthLargest) Add(val int) int { heap.Push(kl, val) if kl.Len() > kl.k { heap.Pop(kl) } return kl.IntSlice[0] } func (kl *KthLargest) Push(v interface{}) { kl.IntSlice = append(kl.IntSlice, v.(int)) } func (kl *KthLargest) Pop() interface{} { a := kl.IntSlice v := a[len(a)-1] kl.IntSlice = a[:len(a)-1] return v } func KthLargestStream(k int, nums []int, elem []int) []int { obj := Constructor(k, nums) result := []int{0} for _, val := range elem { obj.Add(val) result = append(result, obj.IntSlice[0]) } return result } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0704.Binary-Search/":{"url":"Leetcode/0704.Binary-Search/","title":"0704.Binary Search","summary":null,"keywords":"","body":"704. Binary Search tagsstart Easy Binary Search tagsstop ้กŒ็›ฎ Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. You must write an algorithm with O(log n) runtime complexity. Example 1: Input: nums = [-1,0,3,5,9,12], target = 9 Output: 4 Explanation: 9 exists in nums and its index is 4 Example 2: Input: nums = [-1,0,3,5,9,12], target = 2 Output: -1 Explanation: 2 does not exist in nums so return -1 Constraints: 1 -104 All the integers in nums are unique. nums is sorted in ascending order. ้กŒ็›ฎๅคงๆ„ ็ตฆไธ€ๅ€‹ๅทฒๆŽ’ๅบ้ŽๅพŒ็š„array, ๆ‰พๅ‡บtargetๆ‰€ๅœจindex ่‹ฅๆœชๆ‰พๅˆฐๅ›žๅ‚ณ -1 ่งฃ้กŒๆ€่ทฏ ๆ็คบ๏ผš ไพ†ๆบ https://leetcode.com/problems/binary-search/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0704.Binary-Search/main.go package binarysearch import \"sort\" func Search(nums []int, target int) int { lenght := len(nums) if lenght target { // ๆ‰พๅทฆ้‚Š right = mid - 1 } } // ้ƒฝๆฒ’ๆ‰พๅˆฐ return -1 } func Search2(nums []int, target int) int { lenght := len(nums) if lenght >1 mid := int(uint(right+left) >> 1) if nums[mid] == target { return mid } else if nums[mid] target { // ๆ‰พๅทฆ้‚Š right = mid - 1 } } // ้ƒฝๆฒ’ๆ‰พๅˆฐ return -1 } // ๅ…งๅปบsort func BinarySearch(nums []int, target int) int { length := len(nums) index := sort.Search(length, func(i int) bool { return nums[i] >= target }) if index > 1) if nums[middle] == target { return middle } else if target > nums[middle] { return BinarySearchRecursively(nums, target, middle+1, end) } else { return BinarySearchRecursively(nums, target, start, middle-1) } } // ๆœ‰้ปž้กžไผผ nums ๅฐๆ–ผ target็š„ๅ…ƒ็ด ๆœ‰ๅนพๅ€‹ func LeftBound(nums []int, target int) (index int) { lenght := len(nums) if lenght >1 mid := int(uint(right+left) >> 1) if nums[mid] == target { // ่ฆ็นผ็บŒๆ‰พๅทฆ้‚Š, ๆ‰€ไปฅๆŠŠๅณ้‚Š่ฎŠๅฐ right = mid - 1 } else if nums[mid] target { // ๆ‰พๅทฆ้‚Š right = mid - 1 } } // ้ƒฝๆฒ’ๆ‰พๅˆฐ ๆณจๆ„: left่ถŠ็•Œๆƒ…ๆณ if left >= lenght || nums[left] != target { return -1 } return left } func RightBound(nums []int, target int) (index int) { lenght := len(nums) if lenght >1 mid := int(uint(right+left) >> 1) if nums[mid] == target { // ๆณจๆ„:่ฆ็นผ็บŒๆ‰พๅณ้‚Š, ๆ‰€ไปฅๆŠŠๅทฆ้‚Š่ฎŠๅคง=mid+1 left = mid + 1 } else if nums[mid] target { // ๆ‰พๅทฆ้‚Š right = mid - 1 } } // ้ƒฝๆฒ’ๆ‰พๅˆฐ ๆณจๆ„:right่ถŠ็•Œๆƒ…ๆณ if right tags: Easy Leetcode Binary Search ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0721.Accounts-Merge/":{"url":"Leetcode/0721.Accounts-Merge/","title":"0721.Accounts Merge","summary":null,"keywords":"","body":"721. Accounts Merge tagsstart Easy Union Find tagsstop ้ข˜็›ฎ Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name, and the rest of the elements are emailsrepresenting emails of the account. Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people as people could have the same name. A person can have any number of accounts initially, but all of their accounts definitely have the same name. After merging the accounts, return the accounts in the following format: the first element of each account is the name, and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order. Example 1: Input: accounts = [[\"John\", \"johnsmith@mail.com\", \"john00@mail.com\"], [\"John\", \"johnnybravo@mail.com\"], [\"John\", \"johnsmith@mail.com\", \"john_newyork@mail.com\"], [\"Mary\", \"mary@mail.com\"]] Output: [[\"John\", 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com'], [\"John\", \"johnnybravo@mail.com\"], [\"Mary\", \"mary@mail.com\"]] Explanation: The first and third John's are the same person as they have the common email \"johnsmith@mail.com\". The second John and Mary are different people as none of their email addresses are used by other accounts. We could return these lists in any order, for example the answer [['Mary', 'mary@mail.com'], ['John', 'johnnybravo@mail.com'], ['John', 'john00@mail.com', 'john_newyork@mail.com', 'johnsmith@mail.com']] would still be accepted. Note: The length of accounts will be in the range [1, 1000]. The length of accounts[i] will be in the range [1, 10]. The length of accounts[i][j] will be in the range [1, 30]. ้กŒ็›ฎๅคงๆ„ ็ตฆๅฎšไธ€ๅ€‹ๅˆ—่กจ accounts๏ผŒๆฏๅ€‹ๅ…ƒ็ด  accounts[i] ๆ˜ฏไธ€ๅ€‹ๅญ—็ฌฆไธฒๅˆ—่กจ๏ผŒๅ…ถไธญ็ฌฌไธ€ๅ€‹ๅ…ƒ็ด  accounts[i][0] ๆ˜ฏ ๅ็จฑ (name)๏ผŒๅ…ถ้ค˜ๅ…ƒ็ด ๆ˜ฏ emails ่กจ็คบ่ฉฒ่ณฌๆˆถ็š„้ƒต็ฎฑๅœฐๅ€ใ€‚ ็พๅœจ๏ผŒๆˆ‘ๅ€‘ๆƒณๅˆไฝต้€™ไบ›่ณฌๆˆถใ€‚ๅฆ‚ๆžœๅ…ฉๅ€‹่ณฌๆˆถ้ƒฝๆœ‰ไธ€ไบ›ๅ…ฑๅŒ็š„้ƒต็ฎฑๅœฐๅ€๏ผŒๅ‰‡ๅ…ฉๅ€‹่ณฌๆˆถๅฟ…ๅฎšๅฑฌๆ–ผๅŒไธ€ๅ€‹ไบบใ€‚่ซ‹ๆณจๆ„๏ผŒๅณไฝฟๅ…ฉๅ€‹่ณฌๆˆถๅ…ทๆœ‰็›ธๅŒ็š„ๅ็จฑ๏ผŒๅฎƒๅ€‘ไนŸๅฏ่ƒฝๅฑฌๆ–ผไธๅŒ็š„ไบบ๏ผŒๅ› ็‚บไบบๅ€‘ๅฏ่ƒฝๅ…ทๆœ‰็›ธๅŒ็š„ๅ็จฑใ€‚ไธ€ๅ€‹ไบบๆœ€ๅˆๅฏไปฅๆ“ๆœ‰ไปปๆ„ๆ•ธ้‡็š„่ณฌๆˆถ๏ผŒไฝ†ๅ…ถๆ‰€ๆœ‰่ณฌๆˆถ้ƒฝๅ…ทๆœ‰็›ธๅŒ็š„ๅ็จฑใ€‚ ๅˆไฝต่ณฌๆˆถๅพŒ๏ผŒๆŒ‰ไปฅไธ‹ๆ ผๅผ่ฟ”ๅ›ž่ณฌๆˆถ๏ผšๆฏๅ€‹่ณฌๆˆถ็š„็ฌฌไธ€ๅ€‹ๅ…ƒ็ด ๆ˜ฏๅ็จฑ๏ผŒๅ…ถ้ค˜ๅ…ƒ็ด ๆ˜ฏๆŒ‰ๅญ—็ฌฆ ASCII ้ †ๅบๆŽ’ๅˆ—็š„้ƒต็ฎฑๅœฐๅ€ใ€‚่ณฌๆˆถๆœฌ่บซๅฏไปฅไปฅไปปๆ„้ †ๅบ่ฟ”ๅ›žใ€‚ ่งฃ้กŒๆ€่ทฏ ็ตฆๅ‡บไธ€ๅ †่ณฌๆˆถๅ’Œๅฐๆ‡‰็š„้ƒต็ฎฑใ€‚่ฆๆฑ‚ๅˆไฝตๅŒไธ€ๅ€‹ไบบ็š„ๅคšๅ€‹้ƒต็ฎฑ่ณฌๆˆถใ€‚ ๅฆ‚ๆžœ้€™ๅ€‹ไบบๅๅ’Œๆ‰€ๅฑฌ็š„ๅ…ถไธญไน‹ไธ€็š„้ƒต็ฎฑๆ˜ฏ็›ธๅŒ็š„๏ผŒๅฐฑๅˆคๅฎš้€™ๆ˜ฏๅŒไธ€ๅ€‹ไบบ็š„้ƒต็ฎฑ๏ผŒ้‚ฃ้บผๅฐฑๅˆไฝต้€™ไบ›้ƒต็ฎฑใ€‚ ้€™้กŒ็š„่งฃ้กŒๆ€่ทฏๆ˜ฏไธฆๆŸฅ้›†ใ€‚ไธ้Žๅฆ‚ๆžœ็”จๆšดๅŠ›ๅˆไฝต็š„ๆ–นๆณ•๏ผŒๆ™‚้–“่ค‡้›œๅบฆ้žๅธธๅทฎใ€‚ๅ„ชๅŒ–ๆ–นๆณ•ๆ˜ฏๅ…ˆๆŠŠๆฏ็ต„ๆ•ธๆ“š้ƒฝ้€ฒ่กŒ็ทจ่™Ÿ๏ผŒไบบ็ทจ่™Ÿ๏ผŒๆฏๅ€‹้ƒต็ฎฑ้ƒฝ้€ฒ่กŒ็ทจ่™Ÿใ€‚้€™ๅ€‹ๆ˜ ๅฐ„้—œไฟ‚็”จ map ่จ˜้Œ„่ตทไพ†ใ€‚ๅฆ‚ๆžœๅˆฉ็”จไธฆๆŸฅ้›†็š„ union() ๆ“ไฝœ๏ผŒๆŠŠ้€™ไบ›็ทจ่™Ÿ้ƒฝ้€ฒ่กŒๅˆไฝตใ€‚ๆœ€ๅพŒๆŠŠไบบ็š„็ทจ่™Ÿๅ’Œๅฐๆ‡‰้ƒต็ฎฑ็š„็ทจ่™Ÿๆ‹ผๆŽฅ่ตทไพ†ใ€‚ ้€™ไธ€้กŒๆœ‰ 2 ่™•ๆฏ”่ผƒโ€œๅ‘โ€็š„ๆ˜ฏ๏ผŒไธ้œ€่ฆๅˆไฝต็š„็”จๆˆถ็š„้ƒต็ฎฑๅˆ—่กจไนŸๆ˜ฏ้œ€่ฆๆŽ’ๅบๅ’ŒๅŽป้‡็š„๏ผŒๅŒไธ€ๅ€‹ไบบ็š„ๆ‰€ๆœ‰้ƒต็ฎฑ้›†ๅˆ้ƒฝ่ฆๅˆไฝตๅˆฐไธ€่ตทใ€‚ๅ…ท้ซ”่ฆ‹ๆธฌ่ฉฆ็”จไพ‹ใ€‚ไธ้Ž้กŒ็›ฎไธญไนŸๆๅˆฐไบ†้€™ไบ›้ปž๏ผŒไนŸไธ่ƒฝ็ฎ—้กŒ็›ฎๅ‘๏ผŒๅช่ƒฝๆญธ่‡ชๅทฑๆฒ’ๆณจๆ„้€™ไบ›้‚Š็•Œๆƒ…ๆณใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0721.Accounts-Merge/ ๆ™‚้–“่ค‡้›œๅบฆ๏ผšO(n log n) ๅ…ถไธญ n ๆ˜ฏไธๅŒ้ƒต็ฎฑๅœฐๅ€็š„ๆ•ธ้‡ใ€‚ ้œ€่ฆ้ๆญทๆ‰€ๆœ‰้ƒต็ฎฑๅœฐๅ€๏ผŒๅœจไธฆๆŸฅ้›†ๅ…ง้€ฒ่กŒๆŸฅๆ‰พๅ’Œๅˆไฝตๆ“ไฝœ๏ผŒๅฐๆ–ผๅ…ฉๅ€‹ไธๅŒ็š„้ƒต็ฎฑๅœฐๅ€๏ผŒ ๅฆ‚ๆžœๅฎƒๅ€‘็š„็ฅ–ๅ…ˆไธๅŒๅ‰‡้œ€่ฆ้€ฒ่กŒๅˆไฝต๏ผŒ้œ€่ฆ้€ฒ่กŒ 2 ๆฌกๆŸฅๆ‰พๅ’Œๆœ€ๅคš 1 ๆฌกๅˆไฝตใ€‚ไธ€ๅ…ฑ้œ€่ฆ้€ฒ่กŒ 2n ๆฌกๆŸฅๆ‰พๅ’Œๆœ€ๅคš n ๆฌกๅˆไฝต๏ผŒ ๅ› ๆญคๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏ O(2n log n) = O(n log n)ใ€‚ ้€™่ฃก็š„ไธฆๆŸฅ้›†ไฝฟ็”จไบ†่ทฏๅพ‘ๅฃ“็ธฎ๏ผŒไฝ†ๆ˜ฏๆฒ’ๆœ‰ไฝฟ็”จๆŒ‰็งฉๅˆไฝต๏ผŒ ๆœ€ๅฃžๆƒ…ๆณไธ‹็š„ๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏO(n log n)๏ผŒๅนณๅ‡ๆƒ…ๆณไธ‹็š„ๆ™‚้–“่ค‡้›œๅบฆไพ็„ถๆ˜ฏ O(nฮฑ(n))๏ผŒๅ…ถไธญฮฑ ็‚บ้˜ฟๅ…‹ๆ›ผๅ‡ฝๆ•ธ็š„ๅๅ‡ฝๆ•ธ๏ผŒฮฑ(n) ๅฏไปฅ่ช็‚บๆ˜ฏไธ€ๅ€‹ๅพˆๅฐ็š„ๅธธๆ•ธใ€‚ ๆ•ด็†ๅ‡บ้กŒ็›ฎ่ฆๆฑ‚็š„่ฟ”ๅ›ž่ณฌๆˆถ็š„ๆ ผๅผๆ™‚้œ€่ฆๅฐ้ƒต็ฎฑๅœฐๅ€ๆŽ’ๅบ๏ผŒๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏ O(n log n)ใ€‚ ๅ…ถ้ค˜ๆ“ไฝœๅŒ…ๆ‹ฌ้ๆญทๆ‰€ๆœ‰้ƒต็ฎฑๅœฐๅ€๏ผŒๅœจๅ“ˆๅธŒ่กจไธญ่จ˜้Œ„็›ธๆ‡‰็š„ไฟกๆฏ๏ผŒๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏO(n)๏ผŒ ๅœจๆผธ้€ฒๆ„็พฉไธ‹O(n) ๅฐๆ–ผO(nlog n)ใ€‚ ๅ› ๆญค็ธฝๆ™‚้–“่ค‡้›œๅบฆๆ˜ฏ O(n log n)ใ€‚ ไฝœ่€…๏ผšLeetCode-Solution ้ˆๆŽฅ๏ผšhttps://leetcode-cn.com/problems/accounts-merge/solution/zhang-hu-he-bing-by-leetcode-solution-3dyq/ ไพ†ๆบ๏ผšๅŠ›ๆ‰ฃ๏ผˆLeetCode๏ผ‰ ่‘—ไฝœๆฌŠๆญธไฝœ่€…ๆ‰€ๆœ‰ใ€‚ๅ•†ๆฅญ่ฝ‰่ผ‰่ซ‹่ฏ็นซไฝœ่€…็ฒๅพ—ๆŽˆๆฌŠ๏ผŒ้žๅ•†ๆฅญ่ฝ‰่ผ‰่ซ‹่จปๆ˜Žๅ‡บ่™•ใ€‚ ไพ†ๆบ https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0721.Accounts-Merge/ https://leetcode-cn.com/problems/accounts-merge/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0721.Accounts-Merge/Accounts-Merge.go package accountsmerge import ( \"LeetcodeGolang/template\" \"sort\" ) // TODO: ๅ„ชๅŒ– func AccountsMerge(accounts [][]string) (result [][]string) { // result := [][]string{} emailToIndex := map[string]int{} emailToName := map[string]string{} indexToEmails := map[int][]string{} for _, account := range accounts { name := account[0] for _, email := range account[1:] { if _, has := emailToIndex[email]; !has { // ็ด€้Œ„ email, ๅฐๅฏซๅ…ฅๅˆฐ ๅฐๆ‡‰็š„index ่ทŸ ๅฐๆ‡‰็š„user name emailToIndex[email] = len(emailToIndex) emailToName[email] = name } } } parent := make([]int, len(emailToIndex)) // ๅˆๅง‹ๅŒ– for i := range parent { parent[i] = i } var find func(int) int find = func(x int) int { if parent[x] != x { // ้ž่ฟดไธ€็›ดๆ‰พไธ‹ๅŽป parent[x] = find(parent[x]) } return parent[x] } union := func(from, to int) { parent[find(from)] = find(to) } for _, account := range accounts { firstIndex := emailToIndex[account[1]] for _, email := range account[2:] { union(emailToIndex[email], firstIndex) } } for email, index := range emailToIndex { index = find(index) indexToEmails[index] = append(indexToEmails[index], email) } for _, emails := range indexToEmails { for i := 0; i ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0733.Flood-Fill/":{"url":"Leetcode/0733.Flood-Fill/","title":"0733.Flood Fill","summary":"0733.Flood Fill","keywords":"","body":"0733.Flood Fill tagsstart LeetCode Go Easy Flood Fill BFS DFS tagsstop ้กŒ็›ฎ An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image. You are also given three integers sr,sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc]. To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color. Return the modified image after performing the flood fill. Example 1: Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel. Example 2: Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0 Output: [[0,0,0],[0,0,0]] Explanation: The starting pixel is already colored 0, so no changes are made to the image. Constraints: m == image.length n == image[i].length 1 0 0 0 ้กŒ็›ฎๅคงๆ„ ๆœ‰ไธ€ๅ€‹ไปฅไบŒ็ถญๆ•ดๆ•ธ้™ฃๅˆ—่กจ็คบ็š„ๅœ–็•ซ๏ผŒๆฏๅ€‹ๆ•ดๆ•ธ่กจ็คบ่ฉฒๅœ–็•ซ็š„ๅƒ็ด ๅ€ผๅคงๅฐ๏ผŒๆ•ธๅ€ผๅœจ 0 ๅˆฐ 65535 ไน‹้–“ใ€‚ ็ตฆไฝ ไธ€ๅ€‹ๅๆจ™ (sr, sc) ่กจ็คบๅœ–ๅƒๆธฒๆŸ“้–‹ๅง‹็š„ๅƒ็ด ๅ€ผ๏ผˆ่กŒ ๏ผŒๅˆ—๏ผ‰ๅ’Œไธ€ๅ€‹ๆ–ฐ็š„้ก่‰ฒๅ€ผๆ–ฐ้ก่‰ฒ๏ผŒ่ฎ“ๆ‚จ้‡ๆ–ฐไธŠ่‰ฒ่ฉฒๅน…ๅœ–ๅƒใ€‚ ็‚บไบ†ๅฎŒๆˆไธŠ้ก่‰ฒๅทฅไฝœ๏ผŒๅพžไธปๆฟๅๆจ™้–‹ๅง‹๏ผŒ่จ˜้Œ„ไธปๆฟๅๆจ™็š„ไธŠไธ‹ๅ››ๅ€‹ๆ–นๅ‘ไธŠๅƒ็ด ๅ€ผ่ˆ‡ไธปๆฟๅๆจ™็›ธๅŒ็š„ๅฎŒๆ•ดๅƒ็ด ้ปž๏ผŒ้€ฃๆŽฅๅ†่จ˜้Œ„้€™ๅ››ๅ€‹ๆ–นๅ‘ไธŠๆขไปถ็ฌฆๅˆ็š„ๅƒ็ด ้ปž่ˆ‡ๅฎƒๅ€‘ๅฐๆ‡‰็š„ๅ››ๅ€‹ๅƒ็ด ้ปžๆ–นๅ‘ไธŠๅƒ็ด ๅ€ผ่ˆ‡ไธปๆฟๅๆจ™็š„้€ฃ้€šๅƒ็ด ้ปž็›ธๅŒ๏ผŒโ€ฆโ€ฆ๏ผŒ้‡่ค‡่ฉฒ้Ž็จ‹ใ€‚ๅฐ‡ๆ‰€ๆœ‰ๆœ‰่จ˜้Œ„็š„ๅƒ็ด ้ปž็š„้ก่‰ฒๅ€ผๆ”น็‚บๆ–ฐ็š„้ก่‰ฒๅ€ผใ€‚ๆœ€ๅพŒ่ฟ”ๅ›ž็ถ“้ŽไธŠ้ก่‰ฒๆธฒๆŸ“ๅพŒ็š„ๅœ–ๅƒใ€‚ ๆณจๆ„๏ผš image ๅ’Œ image[0] ็š„้•ทๅบฆๅœจ็ฏ„ๅœ [1, 50] ๅ…งใ€‚ ็ตฆๅ‡บ็š„ๅˆๅง‹้ปžๅฐ‡ๆปฟ่ถณ 0 image[i][j] ๅ’Œ newColor ่กจ็คบ็š„้ก่‰ฒๅ€ผๅœจ็ฏ„ๅœ [0, 65535] ๅ…งใ€‚ ่งฃ้กŒๆ€่ทฏ ไธ€ๅ€‹็ตฆๅ‡บไบŒ็ถญ็š„ๅœ–็‰‡้ปž้™ฃ๏ผŒๆฏๅ€‹้ปž้™ฃ้ƒฝๆœ‰ไธ€ๅ€‹ๆ•ธๅญ—ใ€‚็ตฆๅ‡บ่ตท้ปžไธ€ๅ€‹ๅๆจ™๏ผŒ่ฆๆฑ‚ๅพž้€™ๅ€‹่ตท้ปžๅๆจ™้–‹ๅง‹๏ผŒๆŠŠๆ‰€ๆœ‰่ˆ‡้€™ๅ€‹่ตท้ปž่จญ็ฝฎ็š„้ปž้ƒฝๆŸ“่‰ฒๆˆๆ–ฐ็š„้ก่‰ฒใ€‚ ้€™้กŒๆ˜ฏๆจ™ๆบ–็š„ๆดชๆฐดๅกซๅ……็ฎ—ๆณ•ใ€‚ๅฏไปฅ็”จ DFS ไนŸๅฏไปฅ็”จ BFS ใ€‚ BFSๆฏ”่ผƒ้ฉๅˆๆ‰พๆœ€็Ÿญ่ทฏๅพ‘๏ผŒDFSๆฏ”่ผƒ้ฉๅˆๆ‰พๆ‰€ๆœ‰่ทฏๅพ‘ DFSไฝฟ็”จ้ž่ฟดๆฏ”่ผƒๅฅฝๅฏซ ไฝฟ็”จDFS็š„่งฃๆณ•๏ผš ๆชขๆŸฅ่ตทๅง‹้ปž็š„้ก่‰ฒๆ˜ฏๅฆ็ญ‰ๆ–ผๆ–ฐ็š„้ก่‰ฒ๏ผŒๅฆ‚ๆžœๆ˜ฏๅ‰‡็›ดๆŽฅ่ฟ”ๅ›žๅœ–ๅƒใ€‚ ๅ‘ผๅซๆทฑๅบฆๅ„ชๅ…ˆๆœ็ดขๅ‡ฝๆ•ธdfs๏ผŒๅ‚ณๅ…ฅ่ตทๅง‹้ปžๅบงๆจ™srๅ’Œscใ€‚ ๅœจdfsๅ‡ฝๆ•ธไธญ๏ผŒๆชขๆŸฅ็•ถๅ‰ๅบงๆจ™็š„้ก่‰ฒๆ˜ฏๅฆ็ญ‰ๆ–ผ่ตทๅง‹้ปž็š„้ก่‰ฒ๏ผŒๅฆ‚ๆžœๆ˜ฏๅ‰‡ๅฐ‡ๅ…ถ้ก่‰ฒไฟฎๆ”น็‚บๆ–ฐ็š„้ก่‰ฒใ€‚ ้ž่ฟดๅœฐๅฐ็•ถๅ‰ๅบงๆจ™็š„ๅ››ๅ€‹็›ธ้„ฐๆ–นๆ ผ้€ฒ่กŒdfsใ€‚ ่ฟ”ๅ›žๅกซๅ……ๅฎŒๆˆ็š„ๅœ–ๅƒใ€‚ ๆ™‚้–“่ค‡้›œๅบฆ: ๅœ–ๅƒไธญ็š„ๆฏๅ€‹ๆ–นๆ ผๆœ€ๅคš่ขซ่จชๅ•ไธ€ๆฌก๏ผŒๅ› ๆญคๆ™‚้–“่ค‡้›œๅบฆ็‚บO(mn)๏ผŒๅ…ถไธญmๅ’Œnๅˆ†ๅˆฅ็‚บๅœ–ๅƒ็š„่กŒๆ•ธๅ’Œๅˆ—ๆ•ธใ€‚ ็ฉบ้–“่ค‡้›œๅบฆ: ไฝฟ็”จไบ†้ž่ฟด่ชฟ็”จ็š„ๆ ˆ็ฉบ้–“๏ผŒ็ฉบ้–“่ค‡้›œๅบฆ็‚บO(mn)ใ€‚ ไฝฟ็”จBFS็š„่งฃ้กŒๆ€่ทฏๅฆ‚ไธ‹๏ผš ๆชขๆŸฅ่ตทๅง‹้ปž็š„้ก่‰ฒๆ˜ฏๅฆ็ญ‰ๆ–ผๆ–ฐ็š„้ก่‰ฒ๏ผŒๅฆ‚ๆžœๆ˜ฏๅ‰‡็›ดๆŽฅ่ฟ”ๅ›žๅœ–ๅƒใ€‚ ๅ‰ตๅปบไธ€ๅ€‹้šŠๅˆ—๏ผŒๅฐ‡่ตทๅง‹้ปž็š„ๅบงๆจ™(sr, sc)ๅŠ ๅ…ฅ้šŠๅˆ—ไธญใ€‚ ๅ‰ตๅปบไธ€ๅ€‹่จชๅ•้Ž็š„้›†ๅˆ๏ผŒๅฐ‡่ตทๅง‹้ปž็š„ๅบงๆจ™(sr, sc)ๆทปๅŠ ๅˆฐ้›†ๅˆไธญ๏ผŒ่กจ็คบๅทฒ็ถ“่จชๅ•้Žใ€‚ ้€ฒๅ…ฅBFSๅพช็’ฐ๏ผŒ็•ถ้šŠๅˆ—ไธ็‚บ็ฉบๆ™‚๏ผŒๅŸท่กŒไปฅไธ‹ๆ“ไฝœ๏ผš ๅพž้šŠๅˆ—ไธญๅ–ๅ‡บไธ€ๅ€‹ๅบงๆจ™(current_r, current_c)ใ€‚ ๆชขๆŸฅ่ฉฒๅบงๆจ™็š„้ก่‰ฒๆ˜ฏๅฆ็ญ‰ๆ–ผ่ตทๅง‹้ปž็š„้ก่‰ฒ๏ผŒๅฆ‚ๆžœๆ˜ฏ๏ผŒๅฐ‡่ฉฒๅบงๆจ™็š„้ก่‰ฒไฟฎๆ”น็‚บๆ–ฐ็š„้ก่‰ฒใ€‚ ๆชขๆŸฅ่ฉฒๅบงๆจ™็š„ๅ››ๅ€‹็›ธ้„ฐๆ–นๆ ผ๏ผŒๅฆ‚ๆžœ็›ธ้„ฐๆ–นๆ ผ็š„ๅบงๆจ™ๆœ‰ๆ•ˆไธ”้ก่‰ฒ็ญ‰ๆ–ผ่ตทๅง‹้ปž็š„้ก่‰ฒ๏ผŒไธ”่ฉฒ็›ธ้„ฐๆ–นๆ ผ็š„ๅบงๆจ™้‚„ๆฒ’ๆœ‰่ขซ่จชๅ•้Ž๏ผŒๅ‰‡ๅฐ‡่ฉฒ็›ธ้„ฐๆ–นๆ ผ็š„ๅบงๆจ™ๅŠ ๅ…ฅ้šŠๅˆ—ไธญ๏ผŒๅŒๆ™‚ๅฐ‡่ฉฒ็›ธ้„ฐๆ–นๆ ผ็š„ๅบงๆจ™ๆทปๅŠ ๅˆฐ่จชๅ•้Ž็š„้›†ๅˆไธญใ€‚ ้‡่ค‡ไปฅไธŠๆญฅ้ฉŸ๏ผŒ็›ดๅˆฐ้šŠๅˆ—็‚บ็ฉบใ€‚ ่ฟ”ๅ›žๅกซๅ……ๅฎŒๆˆ็š„ๅœ–ๅƒใ€‚ ๆ™‚้–“่ค‡้›œๅบฆๅ’Œ็ฉบ้–“่ค‡้›œๅบฆ็š„ๅˆ†ๆž่ˆ‡DFS่งฃๆณ•็›ธๅŒใ€‚ ไฝฟ็”จBFS็š„่งฃๆณ•ๅŒๆจฃๅฏไปฅๅฎŒๆˆๆณ›ๆดชๅกซๅ……็š„ไปปๅ‹™๏ผŒไธๅŒ็š„ๆ˜ฏไฝฟ็”จ้šŠๅˆ—ไพ†ไฟๅญ˜ๅพ…่™•็†็š„ๅบงๆจ™๏ผŒ่€Œไธๆ˜ฏไฝฟ็”จ้ž่ฟดๅ‡ฝๆ•ธใ€‚ ไพ†ๆบ https://leetcode.com/problems/flood-fill/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0733.Flood-Fill/main.go package floodfill // DFS func FloodFill(image [][]int, sr int, sc int, color int) [][]int { oldColor := image[sr][sc] if color == oldColor { return image } dfsfill(image, sr, sc, oldColor, color) return image } func dfsfill(image [][]int, row, col, oldColor, newColor int) { // Check if the current pixel is out of bounds or does not have the old color if row = len(image) || col = len(image[0]) || image[row][col] != oldColor { return } // Update the current pixel with the new color image[row][col] = newColor // Recursively perform flood fill on the adjacent pixels dfsfill(image, row-1, col, oldColor, newColor) // Up dfsfill(image, row+1, col, oldColor, newColor) // Down dfsfill(image, row, col-1, oldColor, newColor) // Left dfsfill(image, row, col+1, oldColor, newColor) // Right } type Point struct { row, col int } func FloodFillBFS(image [][]int, sr int, sc int, newColor int) [][]int { // Check if the starting point is out of bounds or already has the new color if sr = len(image) || sc = len(image[0]) || image[sr][sc] == newColor { return image } // Get the old color at the starting point oldColor := image[sr][sc] // Create a queue and enqueue the starting point queue := []Point{{sr, sc}} // Define the directions (up, down, left, right) directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}} // Perform BFS for len(queue) > 0 { // Dequeue a point from the queue point := queue[0] queue = queue[1:] // Update the point with the new color image[point.row][point.col] = newColor // Explore the neighboring pixels for _, dir := range directions { newRow, newCol := point.row+dir[0], point.col+dir[1] // Check if the neighboring pixel is within bounds and has the old color if newRow >= 0 && newRow = 0 && newCol Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0733.Flood-Fill cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkFloodFillDFS-8 384756555 4.486 ns/op 0 B/op 0 allocs/op BenchmarkFloodFillBFS-8 309088303 3.642 ns/op 0 B/op 0 allocs/op PASS ok LeetcodeGolang/Leetcode/0733.Flood-Fill 3.572s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0746.Min-Cost-Climbing-Stairs/":{"url":"Leetcode/0746.Min-Cost-Climbing-Stairs/","title":"746. Min Cost Climbing Stairs","summary":"0746.Min-Cost-Climbing-Stairs","keywords":"","body":"746. Min Cost Climbing Stairs tagsstart LeetCode Go Easy Min Cost Climbing Stairs tagsstop ้กŒ็›ฎ You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps. You can either start from the step with index 0, or the step with index 1. Return the minimum cost to reach the top of the floor. Example 1: Input: cost = [10,15,20] Output: 15 Explanation: You will start at index 1. Pay 15 and climb two steps to reach the top. The total cost is 15. Example 2: Input: cost = [1,100,1,1,1,100,1,1,100,1] Output: 6 Explanation: You will start at index 0. Pay 1 and climb two steps to reach index 2. Pay 1 and climb two steps to reach index 4. Pay 1 and climb two steps to reach index 6. Pay 1 and climb one step to reach index 7. Pay 1 and climb two steps to reach index 9. Pay 1 and climb one step to reach the top. The total cost is 6. Constraints: 2 ้กŒ็›ฎๅคงๆ„ ้™ฃๅˆ—็š„ๆฏๅ€‹็ดขๅผ•ๅš็‚บไธ€ๅ€‹้šŽๆขฏ๏ผŒ็ฌฌ i ๅ€‹้šŽๆขฏๅฐๆ‡‰่‘—ไธ€ๅ€‹้ž่ฒ ๆ•ธ็š„้ซ”ๅŠ›่Šฑ่ฒปๅ€ผ cost[i] ๏ผˆ็ดขๅผ•ๅพž 0 ้–‹ๅง‹๏ผ‰ใ€‚ ๆฏ็•ถไฝ ็ˆฌไธŠไธ€ๅ€‹้šŽๆขฏไฝ ้ƒฝ่ฆ่Šฑ่ฒปๅฐๆ‡‰็š„้ซ”ๅŠ›่Šฑ่ฒปๅ€ผ๏ผŒ็„ถๅพŒไฝ ๅฏไปฅ้ธๆ“‡็นผ็บŒ็ˆฌไธ€ๅ€‹้šŽๆขฏๆˆ–่€…็ˆฌๅ…ฉๅ€‹้šŽๆขฏใ€‚ ๆ‚จ้œ€่ฆๆ‰พๅˆฐ้”ๅˆฐๆจ“ๅฑค้ ‚้ƒจ็š„ๆœ€ไฝŽ่Šฑ่ฒปใ€‚ ๅœจ้–‹ๅง‹ๆ™‚๏ผŒไฝ ๅฏไปฅ้ธๆ“‡ๅพž็ดขๅผ•็‚บ 0 ๆˆ– 1 ็š„ๅ…ƒ็ด ไฝœ็‚บๅˆๅง‹้šŽๆขฏใ€‚ ่งฃ้กŒๆ€่ทฏ cur ่ฎŠๆ•ธๅญ˜ๅ„ฒๅพž็ฌฌ i-2 ๆญฅๅˆฐ้”็ฌฌ i ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒปใ€‚ last ่ฎŠๆ•ธๅญ˜ๅ„ฒๅพž็ฌฌ i-1 ๆญฅๅˆฐ้”็ฌฌ i ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒปใ€‚ ๅœจๆฏๆฌก่ฟญไปฃไธญ๏ผŒๅ‡ฝๆ•ธ้ƒฝๆœƒๆฏ”่ผƒ cur ๅ’Œ last ่ฎŠๆ•ธ็š„ๅ€ผ๏ผŒไธฆ้ธๆ“‡่ผƒๅฐ็š„้‚ฃๅ€‹ๅญ˜ๅ„ฒๅœจ cur ่ฎŠๆ•ธไธญใ€‚ ๅœจ่ฟญไปฃ็ตๆŸๆ™‚๏ผŒlast ่ฎŠๆ•ธๅฐ‡ๅญ˜ๅ„ฒ็ˆฌๅฎŒๆ‰€ๆœ‰ๆจ“ๆขฏ็š„ๆœ€ๅฐ่Šฑ่ฒปใ€‚ cost := []int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1} ่ฟญไปฃ cur last 2 0 1 3 1 2 4 2 2 5 2 3 6 3 3 7 3 4 8 4 4 9 4 5 10 5 6 Big O ๆ™‚้–“่ค‡้›œ : O(n) ็ฉบ้–“่ค‡้›œ : O(1) ไพ†ๆบ https://leetcode.com/problems/min-cost-climbing-stairs/ https://leetcode.cn/problems/min-cost-climbing-stairs/ https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0746.Min-Cost-Climbing-Stairs/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0746.Min-Cost-Climbing-Stairs/main.go package mincostclimbingstairs // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) func MinCostClimbingStairs(cost []int) int { dp := make([]int, len(cost)) dp[0], dp[1] = cost[0], cost[1] for i := 2; i b { return b } return a } // ๆ™‚้–“่ค‡้›œ O(n), ็ฉบ้–“่ค‡้›œ O(1) // ๅ„ชๅŒ– // ไฝฟ็”จไบ†ๅ…ฉๅ€‹่ฎŠๆ•ธcurๅ’Œlast๏ผŒ // cur ่ฎŠๆ•ธๅญ˜ๅ„ฒๅพž็ฌฌ i-2 ๆญฅๅˆฐ้”็ฌฌ i ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒปใ€‚ // last ่ฎŠๆ•ธๅญ˜ๅ„ฒๅพž็ฌฌ i-1 ๆญฅๅˆฐ้”็ฌฌ i ๆญฅ็š„ๆœ€ๅฐ่Šฑ่ฒปใ€‚ // ๆฏ”่ผƒๅ…ฉ็จฎ้ธๆ“‡็š„่Šฑ่ฒป๏ผš // ๅพž็ฌฌ2้šŽ้–‹ๅง‹๏ผˆi := 2๏ผ‰๏ผŒไธ€็›ด่ฟญไปฃๅˆฐๆœ€ๅพŒไธ€้šŽ๏ผˆi cur+cost[i-2] { cur, last = last, cur+cost[i-2] } else { cur, last = last, last+cost[i-1] } // fmt.Printf(\"%-d | %-d | %-d\\n\", i, cur, last) } return last } Benchmark goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs cpu: Intel(R) Core(TM) i5-6400 CPU @ 2.70GHz BenchmarkMinCostClimbingStairs-4 36693742 30.17 ns/op 24 B/op 1 allocs/op BenchmarkMinCostClimbingStairsOptimize-4 405489464 3.091 ns/op 0 B/op 0 allocs/op PASS ok LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs 2.713s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0752.Open-the-Lock/":{"url":"Leetcode/0752.Open-the-Lock/","title":"0752.Open the Lock","summary":null,"keywords":"","body":"752. Open the Lock tagsstart Medium Breadth First Search tagsstop You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot. The lock initially starts at '0000', a string representing the state of the 4 wheels. You are given a list of deadends dead ends, meaning if the lock displays any of these codes, the wheels of the lock will stop turning and you will be unable to open it. Given a target representing the value of the wheels that will unlock the lock, return the minimum total number of turns required to open the lock, or -1 if it is impossible. Example 1: Input: deadends = [\"0201\",\"0101\",\"0102\",\"1212\",\"2002\"], target = \"0202\" Output: 6 Explanation: A sequence of valid moves would be \"0000\" -> \"1000\" -> \"1100\" -> \"1200\" -> \"1201\" -> \"1202\" -> \"0202\". Note that a sequence like \"0000\" -> \"0001\" -> \"0002\" -> \"0102\" -> \"0202\" would be invalid, because the wheels of the lock become stuck after the display becomes the dead end \"0102\". Example 2: Input: deadends = [\"8888\"], target = \"0009\" Output: 1 Explanation: We can turn the last wheel in reverse to move from \"0000\" -> \"0009\". Example 3: Input: deadends = [\"8887\",\"8889\",\"8878\",\"8898\",\"8788\",\"8988\",\"7888\",\"9888\"], target = \"8888\" Output: -1 Explanation: We cannot reach the target without getting stuck. Constraints: 1 deadends[i].length == 4 target.length == 4 target will not be in the list deadends. target and deadends[i] consist of digits only. ้กŒ็›ฎๅคงๆ„ ๆœ‰ไธ€ๅ€‹ๅ››ๅ€‹ๅœ“ๅฝขๆ’ญ็›ค็š„่ฝ‰็›ค้Ž–, ๆฏๅ€‹ๆ’ญ็›คๆœ‰0~9ๅ…ฑ10ๅ€‹ๆ•ธๅญ—, ๆฏๅ€‹ๆ’ญ็›คไธŠไธ‹ๆ—‹่ฝ‰ๅฏไปฅๆŠŠ 0่ฎŠๆˆ9 ๆˆ– 9่ฎŠๆˆ0. ๆฏๆฌกๅช่ƒฝๆ—‹่ฝ‰ไธ€ๅ€‹ๆ’ญ็›ค ๅˆๅง‹็›ดๆŽฅ็‚บ0.ไธ”ๆœ‰ไธ€็ต„ deadends ๆ•ธ็ต„. ไธ่ƒฝๆŽฅๆ•ธๅญ—่ฝ‰ๅˆฐๅ…ถไธญไปปไธ€็ต„. ๅฆ‚ๆžœ็„กๆณ•ๅพ—ๅˆฐ target ๅ›žๅ‚ณ -1 ่งฃ้กŒๆ€่ทฏ ๅพž 0000้–‹ๅง‹่ฝ‰, ่ฝ‰ไธ€ๆฌกๅฏ็ชฎ่ˆ‰ๅ‡บ \"1000\", \"9000\", \"0100\", \"0900\", \"0010\", \"0090\", \"0001\", \"0009\". 8 ็ธฝๅฏ่ƒฝ, ๅ†ไปฅ้€™ๅ…ซ็จฎๅฏ†็ขผ็‚บๅŸบ็คŽ, ๅฐๆฏ็ธฝๅฏ†็ขผๅ†่ฝ‰ไธ€ไธ‹, ็ชฎ่ˆ‰ๅ‡บๆฏๅ€‹ๅฏ่ƒฝ ๅฏไปฅๆŠฝ่ฑกๆˆไธ€ๅ‰ฏๅœ–, ๆฏๅ€‹็ฏ€้ปžๆœ‰8ๅ€‹็›ธ้„ฐ็š„็ฏ€้ปž, ่ฎ“ไฝ ๆฑ‚ๅ‡บๆœ€็Ÿญ่ท้›ข ๆ–นๆณ•ไบŒ: ้‚„ๅฏไปฅ็”จ้›™ๅ‘BFS, ๅพž่ตท้ปž่ทŸ็ต‚้ปž้–‹ๅง‹ๆ“ดๆ•ฃ, ็•ถๅ…ฉ้‚Šๆœ‰ไบค้›†ๆ™‚ๅœๆญข ๆ–นๆณ•ไธ‰: ้›™ๅ‘ BFS ๅ„ชๅŒ–, ๅœจ while ้–‹ๅง‹ๆ™‚ๅšไธ€ๅ€‹ๅˆคๆ–ท. ่ฎ“ๆฏๆฌก้ƒฝ้ธๆ“‡่ผƒๅฐ็š„้›†ๅˆ้€ฒ่กŒๆ“ดๆ•ฃ, ้‚ฃ้บผไฝ”็”จ็š„็ฉบ้–“ๅขž้•ท้€Ÿๅบฆๅฐฑๆœƒๆ…ขไธ€ไบ›, ็›กๅฏ่ƒฝไปฅๆœ€ๅฐ็š„็ฉบ้–“ไปฃๅƒน็”ข็”Ÿ curDepth ๅ’Œ nextDepth ็š„ไบค้›† ็„ก่ซ–ๅ–ฎๅ‘็š„ BFS ๆˆ–ๆ˜ฏ ้›™ๅ‘BFS, ๅ„ชๅŒ–้Ž็š„BFS ็ฉบ้–“่ค‡้›œๅบฆ้ƒฝๆ˜ฏไธ€ๆจฃ็š„ ไพ†ๆบ https://leetcode.com/problems/open-the-lock/ https://books.halfrost.com/leetcode/ChapterFour/0700~0799/0752.Open-the-Lock/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0752.Open-the-Lock/main.go package openthelock // ๆ–นๆณ•ใ„ง: ๅ–ฎๅ‘BFS func OpenLock(deadends []string, target string) int { if target == \"0000\" { return 0 } targetNum := strToInt(target) // ็ด€้Œ„ๅทฒ็ชฎ่ˆ‰้Ž็š„ๅฏ†็ขผ, ้˜ฒๆญข่ตฐๅ›ž้ ญ่ทฏ visited := make([]bool, 10000) visited[0] = true for _, deadend := range deadends { num := strToInt(deadend) if num == 0 { return -1 } visited[num] = true } depth, curDepth, nextDepth := 0, []int16{0}, make([]int16, 0) var nextNum int16 for len(curDepth) > 0 { nextDepth = nextDepth[0:0] // ็•ถๅ‰Queueไธญๆ‰€ๆœ‰็š„็ฏ€้ปžๅ‘ๅค–ๆ“ดๆ•ฃ for _, curNum := range curDepth { // ้ๆญทๅ…ซ็จฎ็ต„ๅˆ for incrementer := int16(1000); incrementer > 0; incrementer /= 10 { nextNum = PlusOne(curNum, incrementer) if nextNum == targetNum { return depth + 1 } if !visited[nextNum] { visited[nextNum] = true nextDepth = append(nextDepth, nextNum) } nextNum = MinusOne(curNum, incrementer) if nextNum == targetNum { return depth + 1 } if !visited[nextNum] { visited[nextNum] = true nextDepth = append(nextDepth, nextNum) } } } curDepth, nextDepth = nextDepth, curDepth // ๅขžๅŠ ๆญฅๆ•ธ depth++ } return -1 } /* Note: Golang set type void struct{} var member void set := make(map[string]void) // New empty set set[\"Foo\"] = member // Add for k := range set { // Loop fmt.Println(k) } delete(set, \"Foo\") // Delete size := len(set) // Size _, exists := set[\"Foo\"] // Membership */ // ๆ–นๆณ•ไบŒ: ้›™ๅ‘BFS. ไธๅœจไฝฟ็”จ Queue่€Œๆ˜ฏ็”จ hashset, ๅฟซ้€Ÿๅˆคๆ–ทๅ…ฉ่€…ๆ˜ฏๅฆไบค้›† // ๅพž่ตท้ปž่ทŸ็ต‚้ปž้–‹ๅง‹ๆ“ดๆ•ฃ, ็•ถๅ…ฉ้‚Šๆœ‰ไบค้›†ๆ™‚ๅœๆญข func OpenLockBiDirection(deadends []string, target string) int { if target == \"0000\" { return 0 } targetNum := strToInt(target) // ็ด€้Œ„ๅทฒ็ชฎ่ˆ‰้Ž็š„ๅฏ†็ขผ, ้˜ฒๆญข่ตฐๅ›ž้ ญ่ทฏ visited := make([]bool, 10000) for _, deadend := range deadends { num := strToInt(deadend) if num == 0 { return -1 } visited[num] = true } depth := 0 // ่ตท้ปž่ทŸ็ต‚้ปžๅˆๅง‹ๅŒ– curDepth := make(map[int16]struct{}) nextDepth := make(map[int16]struct{}) curDepth[0] = struct{}{} nextDepth[targetNum] = struct{}{} var nextNum int16 for len(curDepth) != 0 && len(nextDepth) != 0 { // ๅ„ฒๅญ˜ curDepth ็š„ๆ“ดๆ•ฃ็ตๆžœ tmp := make(map[int16]struct{}) // curDepth็š„็ฏ€้ปžๅ‘ๅค–ๆ“ดๆ•ฃ for curNum := range curDepth { // ๅˆคๆ–ทๆ˜ฏๅฆ้”ๅˆฐ็ต‚้ปž if visited[curNum] { continue } _, exists := nextDepth[curNum] if exists { return depth } visited[curNum] = true // ้ๆญทๅ…ซ็จฎ็ต„ๅˆ for incrementer := int16(1000); incrementer > 0; incrementer /= 10 { nextNum = PlusOne(curNum, incrementer) if !visited[nextNum] { tmp[nextNum] = struct{}{} } nextNum = MinusOne(curNum, incrementer) if !visited[nextNum] { tmp[nextNum] = struct{}{} } } } // ๅฐๆŠ€ๅทง, ้€™่ฃไบคๆ› curDepth, nextDepth . // ไธ‹ไธ€่ผช whiheๆœƒๆ“ดๆ•ฃ nextDepth. // ๆ‰€ไปฅๅช่ฆ้ป˜่ชๆ“ดๆ•ฃcurDepth, ๅฐฑ็›ธ็•ถๆ–ผ่ผชๆตๆ“ดๆ•ฃcurDepth, nextDepth curDepth, nextDepth = nextDepth, tmp // ๅขžๅŠ ๆญฅๆ•ธ depth++ } return -1 } // ๆ–นๆณ•ไธ‰ : ้›™ๅ‘ BFS ๅ„ชๅŒ–, ๅœจ while ้–‹ๅง‹ๆ™‚ๅšไธ€ๅ€‹ๅˆคๆ–ท. ่ฎ“ๆฏๆฌก้ƒฝ้ธๆ“‡่ผƒๅฐ็š„้›†ๅˆ้€ฒ่กŒๆ“ดๆ•ฃ, // ้‚ฃ้บผไฝ”็”จ็š„็ฉบ้–“ๅขž้•ท้€Ÿๅบฆๅฐฑๆœƒๆ…ขไธ€ไบ›, ็›กๅฏ่ƒฝไปฅๆœ€ๅฐ็š„็ฉบ้–“ไปฃๅƒน็”ข็”Ÿ curDepth ๅ’Œ nextDepth ็š„ไบค้›† // ็„ก่ซ–ๅ–ฎๅ‘็š„ BFS ๆˆ–ๆ˜ฏ ้›™ๅ‘BFS, ๅ„ชๅŒ–้Ž็š„BFS ็ฉบ้–“่ค‡้›œๅบฆ้ƒฝๆ˜ฏไธ€ๆจฃ็š„ func OpenLockBiDirectionOptimization(deadends []string, target string) int { if target == \"0000\" { return 0 } targetNum := strToInt(target) // ็ด€้Œ„ๅทฒ็ชฎ่ˆ‰้Ž็š„ๅฏ†็ขผ, ้˜ฒๆญข่ตฐๅ›ž้ ญ่ทฏ visited := make([]bool, 10000) for _, deadend := range deadends { num := strToInt(deadend) if num == 0 { return -1 } visited[num] = true } depth := 0 // ่ตท้ปž่ทŸ็ต‚้ปžๅˆๅง‹ๅŒ– curDepth := make(map[int16]struct{}) nextDepth := make(map[int16]struct{}) curDepth[0] = struct{}{} nextDepth[targetNum] = struct{}{} var nextNum int16 for len(curDepth) != 0 && len(nextDepth) != 0 { if len(curDepth) > len(nextDepth) { curDepth, nextDepth = nextDepth, curDepth } // ๅ„ฒๅญ˜ curDepth ็š„ๆ“ดๆ•ฃ็ตๆžœ tmp := make(map[int16]struct{}) // curDepth็š„็ฏ€้ปžๅ‘ๅค–ๆ“ดๆ•ฃ for curNum := range curDepth { // ๅˆคๆ–ทๆ˜ฏๅฆ้”ๅˆฐ็ต‚้ปž if visited[curNum] { continue } _, exists := nextDepth[curNum] if exists { return depth } visited[curNum] = true // ้ๆญทๅ…ซ็จฎ็ต„ๅˆ for incrementer := int16(1000); incrementer > 0; incrementer /= 10 { nextNum = PlusOne(curNum, incrementer) if !visited[nextNum] { tmp[nextNum] = struct{}{} } nextNum = MinusOne(curNum, incrementer) if !visited[nextNum] { tmp[nextNum] = struct{}{} } } } // ๅฐๆŠ€ๅทง, ้€™่ฃไบคๆ› curDepth, nextDepth . // ไธ‹ไธ€่ผช whiheๆœƒๆ“ดๆ•ฃ nextDepth. // ๆ‰€ไปฅๅช่ฆ้ป˜่ชๆ“ดๆ•ฃcurDepth, ๅฐฑ็›ธ็•ถๆ–ผ่ผชๆตๆ“ดๆ•ฃcurDepth, nextDepth curDepth, nextDepth = nextDepth, tmp // ๅขžๅŠ ๆญฅๆ•ธ depth++ } return -1 } func PlusOne(curNum int16, incrementer int16) (nextNum int16) { digit := (curNum / incrementer) % 10 if digit == 9 { nextNum = curNum - 9*incrementer } else { nextNum = curNum + incrementer } return nextNum } func MinusOne(curNum int16, incrementer int16) (nextNum int16) { digit := (curNum / incrementer) % 10 if digit == 0 { nextNum = curNum + 9*incrementer } else { nextNum = curNum - incrementer } return nextNum } func strToInt(str string) int16 { return int16(str[0]-'0')*1000 + int16(str[1]-'0')*100 + int16(str[2]-'0')*10 + int16(str[3]-'0') } tags: Medium Leetcode BFS ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/0876.Middle-of-the-Linked-List/":{"url":"Leetcode/0876.Middle-of-the-Linked-List/","title":"0876.Middle of the Linked List","summary":null,"keywords":"","body":"876. Middle of the Linked List tagsstart Easy Linked List Two Pointers tagsstop ้กŒ็›ฎ Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node. Example 1: Input: head = [1,2,3,4,5] Output: [3,4,5] Explanation: The middle node of the list is node 3. Example 2: Input: head = [1,2,3,4,5,6] Output: [4,5,6] Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. Constraints: The number of nodes in the list is in the range [1, 100]. 1 ้กŒ็›ฎๅคงๆ„ ๅฐ‹ๆ‰พ็„ก็’ฐ็š„ linked list ็š„ไธญ้–“็ฏ€้ปž ่งฃ้กŒๆ€่ทฏ ไฝฟ็”จ two pointer. ่ฎ“ๅฟซๆŒ‡้‡ๅพ€ๅ‰ๅ…ฉๆญฅ. ๆ…ขๆŒ‡้‡ๅพ€ๅ‰ไธ€ๆญฅ. ็•ถๅฟซๆŒ‡้‡ๅˆฐ้”็›ก้ ญๆ™‚, ๆ…ขๆŒ‡้‡ๅฐฑไฝๆ–ผlinked list็š„ไธญ้–“ไฝ็ฝฎ. ็•ถlinked list็š„้•ทๅบฆ็‚บๅฅ‡ๆ•ธๆ™‚, slowๅ‰›ๅฅฝๅœๅœจไธญ้ปžไฝ็ฝฎ; ๅฆ‚ๆžœ้•ทๅบฆ็‚บๅถๆ•ธ, slowๅœๅœจไธญ้–“ๅๅณ ไพ†ๆบ https://leetcode.com/problems/middle-of-the-linked-list/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/0876.Middle-of-the-Linked-List/main.go package middleofthelinkedlist /** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ type ListNode struct { Val int Next *ListNode } func MiddleNode(head *ListNode) *ListNode { if head == nil || head.Next == nil { return head } fast, slow := head, head for fast.Next != nil && fast.Next.Next != nil { fast = fast.Next.Next slow = slow.Next } // ็ฎ—ๅ‡บ้•ทๅบฆ curr := head length := 0 for curr != nil { length++ curr = curr.Next } if length%2 == 0 { // ๅถๆ•ธ return slow.Next } else { // ๅฅ‡ๆ•ธ return slow } } tags: Medium Leetcode two pointers ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/1046.Last-Stone-Weight/":{"url":"Leetcode/1046.Last-Stone-Weight/","title":"1046. Last Stone Weight","summary":"1046.Last-Stone-Weight","keywords":"","body":"1046. Last Stone Weight tagsstart LeetCode Go Easy Heap Priority Queue Last Stone Weight tagsstop ้กŒ็›ฎ You are given an array of integers stones where stones[i] is the weight of the ith stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights x and y with x If x == y, both stones are destroyed, and If x != y, the stone of weight x is destroyed, and the stone of weight y has new weight y - x. At the end of the game, there is at most one stone left. Return the weight of the last remaining stone. If there are no stones left, return 0. Example 1: Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then, we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then, we combine 2 and 1 to get 1 so the array converts to [1,1,1] then, we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone. Example 2: Input: stones = [1] Output: 1 Constraints: 1 ้กŒ็›ฎๅคงๆ„ ๆœ‰ไธ€ๅ€‹้›†ๅˆ stones๏ผŒๆฏๅ€‹ stone ็š„้‡้‡็”ฑๆญฃๆ•ดๆ•ธ่กจ็คบใ€‚ ๆฏๆฌกๅฏไปฅ้ธๆ“‡ๅ…ฉๅ€‹ไธๅŒ็š„็Ÿณ้ ญ๏ผŒๅฐ‡ๅฎƒๅ€‘ไธ€่ตท็ฒ‰็ขŽ๏ผŒ็„ถๅพŒๅพ—ๅˆฐไธ€ๅ€‹ๆ–ฐ็š„็Ÿณ้ ญ๏ผŒๅ…ถ้‡้‡็‚บๅ…ฉ่€…ไน‹ๅทฎใ€‚ ไฝ ้œ€่ฆ้‡่ค‡้€™ๅ€‹้Ž็จ‹๏ผŒ็›ดๅˆฐ้›†ๅˆไธญๅชๅ‰ฉไธ‹ไธ€ๅ€‹็Ÿณ้ ญ๏ผŒๆˆ–่€…้›†ๅˆไธญๆฒ’ๆœ‰็Ÿณ้ ญ็‚บๆญขใ€‚ ๅœจ้€™ๅ€‹้Ž็จ‹ไธญ๏ผŒๆ‰พๅˆฐๅฏ่ƒฝ็š„ๆœ€ๅพŒไธ€้ก†็Ÿณ้ ญ็š„้‡้‡ใ€‚ๅฆ‚ๆžœ้›†ๅˆไธญๆฒ’ๆœ‰็Ÿณ้ ญ๏ผŒๅ‰‡่ฟ”ๅ›ž 0ใ€‚ Input: stones = [2,7,4,1,8,1] Output: 1 Explanation: ๆญฅ้ฉŸ1๏ผš้ธๆ“‡็Ÿณ้ ญ 7 ๅ’Œ 8๏ผŒๅพ—ๅˆฐๆ–ฐ็Ÿณ้ ญ [2,4,1,1,1]ใ€‚ ๆญฅ้ฉŸ2๏ผš้ธๆ“‡็Ÿณ้ ญ 2 ๅ’Œ 4๏ผŒๅพ—ๅˆฐๆ–ฐ็Ÿณ้ ญ [2,1,1,1]ใ€‚ ๆญฅ้ฉŸ3๏ผš้ธๆ“‡็Ÿณ้ ญ 2 ๅ’Œ 1๏ผŒๅพ—ๅˆฐๆ–ฐ็Ÿณ้ ญ [1,1,1]ใ€‚ ๆญฅ้ฉŸ4๏ผš้ธๆ“‡็Ÿณ้ ญ 1 ๅ’Œ 1๏ผŒๅพ—ๅˆฐๆ–ฐ็Ÿณ้ ญ [0,1]ใ€‚ ๆญฅ้ฉŸ5๏ผš้ธๆ“‡็Ÿณ้ ญ 1 ๅ’Œ 0๏ผŒๅพ—ๅˆฐๆ–ฐ็Ÿณ้ ญ [1]ใ€‚ ๆœ€ๅพŒๅ‰ฉไธ‹็š„็Ÿณ้ ญ็š„้‡้‡็‚บ 1ใ€‚ ่งฃ้กŒๆ€่ทฏ ๅฐ‡ stones ้™ฃๅˆ—่ฝ‰ๆ›็‚บๆœ€ๅคงๅ †๏ผˆmax heap๏ผ‰๏ผŒๅฏไปฅไฝฟ็”จๅ„ชๅ…ˆไฝ‡ๅˆ—ๅฏฆ็พใ€‚ ้€ฒ่กŒ่ฟดๅœˆ๏ผŒๆฏๆฌกๅพžๆœ€ๅคงๅ †ไธญๅ–ๅ‡บๅ…ฉๅ€‹ๆœ€ๅคง็š„็Ÿณ้ ญใ€‚ ๅฆ‚ๆžœๅ…ฉๅ€‹็Ÿณ้ ญไธ็›ธ็ญ‰๏ผŒๅฐ‡ๅฎƒๅ€‘็š„ๅทฎๅ€ผๆ’ๅ…ฅๆœ€ๅคงๅ †ใ€‚ ้‡่ค‡ไธŠ่ฟฐๆญฅ้ฉŸ๏ผŒ็›ดๅˆฐๆœ€ๅคงๅ †ไธญๅชๅ‰ฉไธ‹ไธ€ๅ€‹็Ÿณ้ ญๆˆ–ๆฒ’ๆœ‰็Ÿณ้ ญ็‚บๆญขใ€‚ ๅฆ‚ๆžœๆœ€ๅคงๅ †ไธญๆœ‰็Ÿณ้ ญ๏ผŒ่ฟ”ๅ›ž่ฉฒ็Ÿณ้ ญ็š„้‡้‡๏ผŒๅฆๅ‰‡่ฟ”ๅ›ž 0ใ€‚ ้€™ๆจฃ็š„ๅšๆณ•็ขบไฟๆฏๆฌก้ƒฝ้ธๆ“‡ๆœ€ๅคง็š„ๅ…ฉๅ€‹็Ÿณ้ ญ้€ฒ่กŒ็ฒ‰็ขŽ๏ผŒๆœ€็ต‚็•™ไธ‹็š„็Ÿณ้ ญ้‡้‡ๅฐฑๆ˜ฏๅฏ่ƒฝ็š„ๆœ€ๅพŒไธ€ๅ€‹็Ÿณ้ ญ็š„้‡้‡ใ€‚ ๅƒ่€ƒ 0215 Kth Largest Element in an Array Big O ๆ™‚้–“่ค‡้›œ : O(nlogn) ็ฉบ้–“่ค‡้›œ : O(n) n ๆ˜ฏ็Ÿณ้ ญๆ•ธ้‡. ๆฏๆฌกๅพž้šŠๅˆ—ไธญๅ–ๅ‡บๅ…ƒ็ด ้œ€่ฆ่ฉฑO(logn) ็š„ๆ™‚้–“, ๆœ€ๅคšๅ…ฑ้œ€่ฆ้œ€่ฆ็ฒ‰็ขŽ nโˆ’1 ๆฌก็Ÿณ้ ญ ไพ†ๆบ https://leetcode.com/problems/last-stone-weight/ https://leetcode.cn/problems/last-stone-weight/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/1046.Last-Stone-Weight/main.go package laststoneweight import ( \"container/heap\" \"fmt\" \"sort\" ) /* // IntSlice attaches the methods of Interface to []int, sorting in increasing order. type IntSlice []int func (x IntSlice) Len() int { return len(x) } func (x IntSlice) Less(i, j int) bool { return x[i] h.IntSlice[j] } func (h *hp) Push(v interface{}) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() interface{} { old := h.IntSlice v := old[len(old)-1] h.IntSlice = old[:len(old)-1] return v } func (h *hp) PushInt(v int) { heap.Push(h, v) } func (h *hp) PopInt() int { return heap.Pop(h).(int) } // ๆ™‚้–“่ค‡้›œ O(nlogn), ็ฉบ้–“่ค‡้›œ O(n) // n ๆ˜ฏ็Ÿณ้ ญๆ•ธ้‡. ๆฏๆฌกๅพž้šŠๅˆ—ไธญๅ–ๅ‡บๅ…ƒ็ด ้œ€่ฆ่ฉฑO(logn) ็š„ๆ™‚้–“, ๆœ€ๅคšๅ…ฑ้œ€่ฆ้œ€่ฆ็ฒ‰็ขŽ nโˆ’1 ๆฌก็Ÿณ้ ญ func LastStoneWeight(stones []int) int { q := &hp{stones} heap.Init(q) fmt.Println(q) for q.Len() > 1 { fmt.Println(q) x, y := q.PopInt(), q.PopInt() fmt.Printf(\"%d,%d\\n\", x, y) if x > y { q.PushInt(x - y) } } if q.Len() > 0 { return q.IntSlice[0] } return 0 } Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/1143.Longest-Common-Subsequence/":{"url":"Leetcode/1143.Longest-Common-Subsequence/","title":"1143.Longest Common Subsequence","summary":null,"keywords":"","body":"1143. Longest Common Subsequence tagsstart Medium Dynamic Programming tagsstop ้กŒ็›ฎ Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, \"ace\" is a subsequence of \"abcde\". A common subsequence of two strings is a subsequence that is common to both strings. Example 1: Input: text1 = \"abcde\", text2 = \"ace\" Output: 3 Explanation: The longest common subsequence is \"ace\" and its length is 3. Example 2: Input: text1 = \"abc\", text2 = \"abc\" Output: 3 Explanation: The longest common subsequence is \"abc\" and its length is 3. Example 3: Input: text1 = \"abc\", text2 = \"def\" Output: 0 Explanation: There is no such common subsequence, so the result is 0. Constraints: 1 text1 and text2 consist of only lowercase English characters. ้กŒ็›ฎๅคงๆ„ ็ตฆๅ…ฉๅ€‹string ๆฑ‚ๅ‡บ, ้€™ๅ…ฉๅ€‹string ็š„ๆœ€้•ทๅ…ฌๅ…ฑๅญๅบๅˆ—็š„้•ทๅบฆ, ๅฆ‚ๆžœไธๅญ˜ๅœจ่ฟ”ๅ›ž0. ่ญฌๅฆ‚ str1=\"abcde\", str2=\"aceb\", ่ผธๅ‡บ็‚บ3, ๅ› ็‚บๆœ€้•ทๅ…ฌๅ…ฑๅญๅบๅˆ—ๆ˜ฏ\"ace\" ่งฃ้กŒๆ€่ทฏ ๆšดๅŠ›่งฃๆณ•, ็”จ้ž่ฟด dp(i,j) ่กจ็คบ s1[0..i]ๅ’Œs2[0..j]ไธญๆœ€้•ทๅ…ฌๅ…ฑๅญๅบๅˆ—็š„้•ทๅบฆ, ๅฆ‚ๆžœs1[i]==s2[j], ่ชชๆ˜Ž้€™ๅ€‹ๅ…ฌๅ…ฑๅญ—็ฌฆไธ€ๅฎšๅœจlcsไธญ, ๅฆ‚ๆžœ็Ÿฅ้“ไบ†s1[0..i-1]ๅ’Œs2[0..j-1]ไธญ็š„lcs้•ทๅบฆ, ๅ†ๅŠ 1ๅฐฑๆ˜ฏs1[0..i]ๅ’Œs2[0..j]ไธญlcs็š„้•ทๅบฆ if (str[i] == str2[j]) { dp(i,j) = dp(i-1,j-1)+1 } ๅฆ‚ๆžœs1[i]!=s2[j], ่ชชๆ˜Ž้€™ๅ…ฉๅ€‹ๅญ—็ฌฆ่‡ณๅฐ‘ๆœ‰ไธ€ๅ€‹ไธๅœจlcsไธญ, if (str[i] != str2[j]){ dp(i,j) = max( dp(i-1,j) , dp(i,j-1)) } def longestCommonSubsequence(str1,str2) ->int: def dp(i,j): # ็ฉบ็š„base code if i == -1 or j == -1: return 0 if str[i] == str2[j]: # ๆ‰พๅˆฐไธ€ๅ€‹lcsไธญ็š„ๅ…ƒ็ด  return dp(i-1, j-1)+1 if str[i] != str2[j]: # ่‡ณๅฐ‘ๆœ‰ไธ€ๅ€‹ๅญ—็ฌฆไธๅœจlcsไธญ, ้ƒฝ่ฉฆไธ€ไธ‹,็œ‹่ชฐ่ƒฝ่ฎ“lcsๆœ€้•ท return max( dp(i-1,j) , dp(i,j-1)) return dp(len(str1)-1,len(str2)-1) DPๅ„ชๅŒ– int longestCommonSubsequence(string str1, string str2) { int m = str1.size(), n = str2.size(); // ๅฎš็พฉๅฐs1[0..i-1] ๅ’Œ s2[0..j-1], ไป–ๅ€‘็š„lcs้•ทๅบฆๆ˜ฏdp[i][j] vector> dp(m + 1, vector(n + 1, 0)); // base case: dp[0][...] = dp[..][0] = 0, ๅทฒๅˆๅง‹ๅŒ– for (int i = 1; i ไพ†ๆบ https://leetcode.com/problems/longest-common-subsequence/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/1143.Longest-Common-Subsequence/main.go package longestcommonsubsequence func LongestCommonSubsequence(text1 string, text2 string) int { var dp func(int, int) int dp = func(i, j int) int { if i == -1 || j == -1 { return 0 } if text1[i] == text2[j] { return dp(i-1, j-1) + 1 } if text1[i] != text2[j] { return max(dp(i-1, j), dp(i, j-1)) } return 0 } return dp(len(text1)-1, len(text2)-1) } func LongestCommonSubsequenceDP(text1 string, text2 string) int { m, n := len(text1), len(text2) if m == 0 || n == 0 { return 0 } dp := make([][]int, m+1) for i := range dp { dp[i] = make([]int, n+1) } for i := 1; i b { return a } return b } goos: darwin goarch: amd64 pkg: LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence cpu: Intel(R) Core(TM) i5-8259U CPU @ 2.30GHz BenchmarkLongestCommonSubsequence-8 100 737158262 ns/op 0 B/op 0 allocs/op BenchmarkLongestCommonSubsequenceDP-8 2355297 491.3 ns/op 912 B/op 8 allocs/op PASS ok LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence 75.400s ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Leetcode/1195.Fizz-Buzz-Multithreaded/":{"url":"Leetcode/1195.Fizz-Buzz-Multithreaded/","title":"1195. Fizz Buzz Multithreaded","summary":"1195.Fizz-Buzz-Multithreaded","keywords":"","body":"1195. Fizz Buzz Multithreaded tagsstart LeetCode Go Medium Fizz Buzz Multithreaded Concurrency tagsstop ้กŒ็›ฎ You have the four functions: printFizz that prints the word \"fizz\" to the console, printBuzz that prints the word \"buzz\" to the console, printFizzBuzz that prints the word \"fizzbuzz\" to the console, and printNumber that prints a given integer to the console. You are given an instance of the class FizzBuzz that has four functions: fizz, buzz, fizzbuzz and number. The same instance of FizzBuzz will be passed to four different threads: Thread A: calls fizz() that should output the word \"fizz\". Thread B: calls buzz() that should output the word \"buzz\". Thread C: calls fizzbuzz() that should output the word \"fizzbuzz\". Thread D: calls number() that should only output the integers. Modify the given class to output the series [1, 2, \"fizz\", 4, \"buzz\", ...] where the ith token (1-indexed) of the series is: \"fizzbuzz\" if i is divisible by 3 and 5, \"fizz\" if i is divisible by 3 and not 5, \"buzz\" if i is divisible by 5 and not 3, or i if i is not divisible by 3 or 5. Implement the FizzBuzz class: FizzBuzz(int n) Initializes the object with the number n that represents the length of the sequence that should be printed. void fizz(printFizz) Calls printFizz to output \"fizz\". void buzz(printBuzz) Calls printBuzz to output \"buzz\". void fizzbuzz(printFizzBuzz) Calls printFizzBuzz to output \"fizzbuzz\". void number(printNumber) Calls printnumber to output the numbers. Example 1: Input: n = 15 Output: [1,2,\"fizz\",4,\"buzz\",\"fizz\",7,8,\"fizz\",\"buzz\",11,\"fizz\",13,14,\"fizzbuzz\"] Example 2: Input: n = 5 Output: [1,2,\"fizz\",4,\"buzz\"] Constraints: 1 ้กŒ็›ฎๅคงๆ„ ่งฃ้กŒๆ€่ทฏ Big O ๆ™‚้–“่ค‡้›œ : ็ฉบ้–“่ค‡้›œ : ไพ†ๆบ https://leetcode.com/problems/fizz-buzz-multithreaded/description/ https://leetcode.cn/problems/fizz-buzz-multithreaded/description/ ่งฃ็ญ” https://github.com/kimi0230/LeetcodeGolang/blob/master/Leetcode/1195.Fizz-Buzz-Multithreaded/main.go package fizzbuzzmultithreaded import ( \"fmt\" \"sync\" ) var ( wg = sync.WaitGroup{} ) // ๆ™‚้–“่ค‡้›œ O(), ็ฉบ้–“่ค‡้›œ O() func FizzBuzz(n int) { fb := NewFizzBuzz() wg.Add(4) go fb.fizz() go fb.buzz() go fb.fizzbuzz() go fb.number() for i := 1; i Benchmark ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"structures/":{"url":"structures/","title":"Structures","keywords":"","body":"ไพ†ๆบ https://github.com/halfrost/LeetCode-Go/tree/master/structures ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"structures/heap/index.en.html":{"url":"structures/heap/index.en.html","title":"Golang Container Heap","summary":"0703.Kth-Largest-Element-in-a-Stream","keywords":"","body":"Golang : container/heap tagsstart Go container/heap tagsstop Heapๆ˜ฏไป€้บผ Wiki: https://zh.wikipedia.org/wiki/%E5%A0%86%E7%A9%8D ๅ †็ฉ๏ผˆHeap๏ผ‰ๆ˜ฏ้›ป่…ฆ็ง‘ๅญธไธญ็š„ไธ€็จฎ็‰นๅˆฅ็š„ๅฎŒๅ…จไบŒๅ…ƒๆจนใ€‚ ่‹ฅๆ˜ฏๆปฟ่ถณไปฅไธ‹็‰นๆ€ง๏ผŒๅณๅฏ็จฑ็‚บๅ †็ฉ๏ผšใ€Œ็ตฆๅฎšๅ †็ฉไธญไปปๆ„็ฏ€้ปžPๅ’ŒC๏ผŒ่‹ฅPๆ˜ฏC็š„ๆฏ็ฏ€้ปž๏ผŒ้‚ฃ้บผP็š„ๅ€ผๆœƒๅฐๆ–ผ็ญ‰ๆ–ผ๏ผˆๆˆ–ๅคงๆ–ผ็ญ‰ๆ–ผ๏ผ‰C็š„ๅ€ผใ€ใ€‚ ่‹ฅๆฏ็ฏ€้ปž็š„ๅ€ผๆ†ๅฐๆ–ผ็ญ‰ๆ–ผๅญ็ฏ€้ปž็š„ๅ€ผ๏ผŒๆญคๅ †็ฉ็จฑ็‚บๆœ€ๅฐๅ †็ฉ๏ผˆmin heap๏ผ‰๏ผ› ๅไน‹๏ผŒ่‹ฅๆฏ็ฏ€้ปž็š„ๅ€ผๆ†ๅคงๆ–ผ็ญ‰ๆ–ผๅญ็ฏ€้ปž็š„ๅ€ผ๏ผŒๆญคๅ †็ฉ็จฑ็‚บๆœ€ๅคงๅ †็ฉ๏ผˆmax heap๏ผ‰ใ€‚ ๅœจๅ †็ฉไธญๆœ€้ ‚็ซฏ็š„้‚ฃไธ€ๅ€‹็ฏ€้ปž๏ผŒ็จฑไฝœๆ น็ฏ€้ปž๏ผˆroot node๏ผ‰๏ผŒๆ น็ฏ€้ปžๆœฌ่บซๆฒ’ๆœ‰ๆฏ็ฏ€้ปž๏ผˆparent node๏ผ‰ใ€‚ container/heap ๆไพ›็š„ๆ–นๆณ• heapๅŒ…็‚บๅฏฆ็พไบ† heap.Interface ็š„้กžๅž‹ๆไพ›ไบ†ๅ †ๆ–นๆณ•๏ผšInit/Push/Pop/Remove/Fixใ€‚ container/heap ็‚บๆœ€ๅฐๅ †๏ผŒ ๅณๆฏๅ€‹็ฏ€้ปž็š„ๅ€ผ้ƒฝๅฐๆ–ผๅฎƒ็š„ๅญๆจน็š„ๆ‰€ๆœ‰ๅ…ƒ็ด ็š„ๅ€ผ๏ผˆA heap is a tree with the property that each node is the minimum-valued node in its subtree๏ผ‰ใ€‚ heap: package heap // ... // Note that Push and Pop in this interface are for package heap's // implementation to call. To add and remove things from the heap, // use heap.Push and heap.Pop. type Interface interface { sort.Interface Push(x any) // add x as element Len() Pop() any // remove and return element Len() - 1. } sort: package sort // An implementation of Interface can be sorted by the routines in this package. // The methods refer to elements of the underlying collection by integer index. type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with index i // must sort before the element with index j. // // If both Less(i, j) and Less(j, i) are false, // then the elements at index i and j are considered equal. // Sort may place equal elements in any order in the final result, // while Stable preserves the original input order of equal elements. // // Less must describe a transitive ordering: // - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well. // - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well. // // Note that floating-point comparison (the ็”ฑๆ–ผ heap.Interface ๅŒ…ๅซไบ† sort.Interface ๏ผŒๆ‰€ไปฅ๏ผŒ็›ฎๆจ™้กžๅž‹้œ€่ฆๅŒ…ๅซๅฆ‚ไธ‹ๆ–นๆณ•๏ผšLen/Less/Swap ,Push/Popใ€‚ container/heap ๅฏ็”จๅœจๅ“ช container/heapๅŒ…ๅฏไปฅ็”จไพ†ๆง‹้€ ๅ„ชๅ…ˆ้ †ๅบไฝ‡ๅˆ—ใ€‚ https://go.dev/play/p/77zrF3PurO4 // This example demonstrates a priority queue built using the heap interface. package main import ( \"container/heap\" \"fmt\" ) // An Item is something we manage in a priority queue. type Item struct { value string // The value of the item; arbitrary. priority int // The priority of the item in the queue. // The index is needed by update and is maintained by the heap.Interface methods. index int // The index of the item in the heap. } // A PriorityQueue implements heap.Interface and holds Items. type PriorityQueue []*Item func (pq PriorityQueue) Len() int { return len(pq) } func (pq PriorityQueue) Less(i, j int) bool { // We want Pop to give us the highest, not lowest, priority so we use greater than here. return pq[i].priority > pq[j].priority } func (pq PriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] pq[i].index = i pq[j].index = j } func (pq *PriorityQueue) Push(x interface{}) { n := len(*pq) item := x.(*Item) item.index = n *pq = append(*pq, item) } func (pq *PriorityQueue) Pop() interface{} { old := *pq n := len(old) item := old[n-1] item.index = -1 // for safety *pq = old[0 : n-1] return item } // update modifies the priority and value of an Item in the queue. func (pq *PriorityQueue) update(item *Item, value string, priority int) { item.value = value item.priority = priority heap.Fix(pq, item.index) } PriorityQueue ๆœฌ่ณชไธŠๆ˜ฏๅ€‹ *Item ้™ฃๅˆ—๏ผŒๅ…ถLen/Less/Swapๆ˜ฏๆฏ”่ผƒๅธธ่ฆ‹็š„้™ฃๅˆ—็”จไพ†sort้œ€่ฆๅฎš็พฉ็š„ๅ‡ฝๆ•ธ๏ผŒ่€ŒPushใ€Popๅ‰‡ๆ˜ฏไฝฟ็”จๆ•ธไฝไพ†ๆ’ๅ…ฅใ€็š„ๆ–นๆณ•ใ€‚ PriorityQueue ้‚„ๆไพ›ไบ†updateๆ–นๆณ•ใ€‚ ๆณจๆ„็”ฑๆ–ผ้€šๅธธๅธŒๆœ›ๅ„ชๅ…ˆ้ †ๅบไฝ‡ๅˆ—Popๅ‡บไพ†็š„ๆ˜ฏๅ„ชๅ…ˆ้ †ๅบๆœ€้ซ˜็š„ๅ…ƒ็ด ๏ผŒๆ‰€ไปฅLessๆ–นๆณ•ๆ˜ฏๅ่‘—ๅฏซ็š„ใ€‚ ๅฎš็พฉไบ†ไปฅไธŠๆ–นๆณ•ไปฅๅพŒ๏ผŒ PriorityQueue ๅฐฑๅ…ทๅ‚™ไบ†ไฝฟ็”จ container/heap ๅŒ…็š„ๆขไปถใ€‚ ๅฆ‚ไธ‹ไปฃ็ขผ๏ผŒๅ…ˆๅพžitems mapๅ‡บ็™ผๅฎš็พฉไบ†ไธ€ๅ€‹pq้™ฃๅˆ—๏ผŒ้•ทๅบฆ็‚บhash็š„size๏ผŒไธฆ่ชฟ็”จ heap.Init ๅˆๅง‹ๅŒ–pq; ไน‹ๅพŒๅ‘ไฝ‡ๅˆ—ไธญๅขžๅŠ ไบ†ไธ€ๅ€‹ๅ„ชๅ…ˆ้ †ๅบ็‚บ1็š„ๅ…ƒ็ด ๏ผŒไธฆๆ›ดๆ–ฐ่ฉฒๅ…ƒ็ด ็š„ไฝ‡ๅˆ—; ๆœ€ๅพŒๅพžไฝ‡ๅˆ—ไธญไพๆญคPop๏ผŒๅฏ่ฆ‹ๅ…ƒ็ด ๅœจPopๆ™‚ๆ˜ฏไพ็…งๅ„ชๅ…ˆ้ †ๅบๆŽ’ๅบ็š„ใ€‚ // This example creates a PriorityQueue with some items, adds and manipulates an item, // and then removes the items in priority order. func main() { // Some items and their priorities. items := map[string]int{ \"banana\": 3, \"apple\": 2, \"pear\": 4, } // Create a priority queue, put the items in it, and // establish the priority queue (heap) invariants. pq := make(PriorityQueue, len(items)) i := 0 for value, priority := range items { pq[i] = &Item{ value: value, priority: priority, index: i, } i++ } heap.Init(&pq) // Insert a new item and then modify its priority. item := &Item{ value: \"orange\", priority: 1, } heap.Push(&pq, item) pq.update(item, item.value, 5) // Take the items out; they arrive in decreasing priority order. for pq.Len() > 0 { item := heap.Pop(&pq).(*Item) fmt.Printf(\"%.2d:%s index:%d \\n\", item.priority, item.value, item.index) } } // Output: // 05:orange index:-1 // 04:pear index:-1 // 03:banana index:-1 // 02:apple index:-1 Reference Golang: ่ฏฆ่งฃcontainer/heap ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"template/":{"url":"template/","title":"Template","keywords":"","body":"ไพ†ๆบ https://github.com/halfrost/LeetCode-Go/tree/master/template ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"CHANGELOG.html":{"url":"CHANGELOG.html","title":"CHANGELOG","keywords":"","body":"kk2 ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 "},"Content.html":{"url":"Content.html","title":"Content","keywords":"","body":"Kimi's LeetcodeGolang Notes Algorithms A 1 B 2 C 3 A1B2C3: Two Go Routine Print A1B2C3....Z26 Find Target Last Index Find Target Last Index Intersection Of Two Sorted Arrays Using In Place Approach Intersection Of Two Sorted Arrays Using In Place Approach Search Graph Search Graph In Golang Weighted Edit Distance Code Signal Bank Requests Bank Requests Codility Lesson 0001.Iterations Binary Gap Binary Gap 0002.Array Cyclic Rotation Cyclic Rotation Odd Occurrences In Array 0003.Time-Complexity Frog Jmp Perm Missing Elem Tape Equilibrium 0004.Counting-Elements Frog River One Max Counters Missing Integer Perm Check 0005.Prefix-Sums Count Div Genomic Range Query Min Avg Two Slice Passing Cars 0006.Sorting Distinct Max Product Of Three Number Of Disc Intersections Triangle 0007.Stacks-and-Queues Brackets Fish Nesting Stone Wall 0008.Leader Dominator Equi Leader 0009.Maximum-Slice-Problem Max Double Slice Sum Max Profit Max Slice Sum 0010.Prime-And-Composite-Numbers Count Factors Flags Min Perimeter Rectangle Peaks 0011.Sieve-of-Eratosthenes Count Non Divisible Count Semiprimes 0012.Euclidean-Algorithm Chocolates By Numbers Common Prime Divisors 0013.Fibonacci-Numbers Fib Frog 0015.Caterpillar-Method Abs Distinct Geeksfor Geeks Sorting Algorithms 0031.Find-Minimum-Difference-Between-Any-Two-Elements Leetcode 0000.xxxx NUM.LEETCODETITLE 0001.Two-Sum Merging 2 Packages 0001.Two Sum 0002.Add-Two-Numbers 0002.Add Two Numbers 0003.Longest-Substring-Without-Repeating-Characters 0003.Longest Substring Without Repeating Characters 0005.Longest-Palindromic-Substring 0005. Longest Palindromic Substring 0015.3Sum 0015. 3Sum 0019.Remove-Nth-Node-From-End-of-List 0019. Remove Nth Node From End of List 0020.Valid-Parentheses 0020. Valid Parentheses 0021.Merge-Two-Sorted-Lists 0021. Merge Two Sorted Lists 0027.Remove-Element 0027.Remove Element 0028.Find-the-Index-of-the-First-Occurrence-in-a-String 0028. Find the Index of the First Occurrence in a String 0035.Search-Insert-Position 0035.Search Insert Position 0046.Permutations 0049.Group-Anagrams 0049.Group Anagrams 0053.Maximum-Subarray 0053.Maximum Subarray 0059.Spiral-Matrix-II 0059.Spiral Matrix II 0070.Climbing-Stairs 0070.Climbing Stairs 0072.Edit-Distance 0072. Edit Distance 0075.Sort-Colors 0075.Sort Colors 0078.Subsets 0078. Subsets 0088.Merge-Sorted-Array 0088.Merge Sorted Array 0094.Binary-Tree-Inorder-Traversal 0094.Binary Tree Inorder Traversal 0100.Same-Tree 100. Same Tree 0104.Maximum-Depth-of-Binary-Tree 0104.Maximum Depth of Binary Tree 0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal 105. Construct Binary Tree from Preorder and Inorder Traversal 0110.Balanced-Binary-Tree 110. Balanced Binary Tree 0121.Best-Time-to-Buy-and-Sell-Stock 0121.Best Time to Buy and Sell Stock 0125.Valid-Palindrome 0125. Valid Palindrome 0128.Longest-Consecutive-Sequence 128. Longest Consecutive Sequence 0138.Copy-List-with-Random-Pointer 138. Copy List with Random Pointer 0141.Linked-List-Cycle 0141.Linked List Cycle 0142.Linked-List-CycleII 0142.Linked List Cycle II 0143.Reorder-List 143. Reorder List 0167.Two-Sum-II-Input-Array-Is-Sorted 0167.Two Sum II Input Array Is Sorted 0203.Remove-Linked-List-Elements 0203.Remove Linked List Elements 0206.Reverse-Linked-List 206. Reverse Linked List 0209.Minimum-Size-Subarray-Sum 0209. Minimum Size Subarray Sum 0215.Kth-Largest-Element-in-an-Array 0215. Kth Largest Element in an Array 0217.Contains-Duplicate 0226.Invert-Binary-Tree 226. Invert Binary Tree 0238.Product-of-Array-Except-Self 238. Product of Array Except Self 0242.Valid-Anagram 0283.Move-Zeroes 0283. Move Zeroes 0300.Longest-Increasing-Subsequence 0300.Longest Increasing Subsequence 0310.Minimum-Height-Trees 0310.Minimum Height Trees 0322.Coin-Change 0322.Coin Change 0344.Reverse-String 0344.Reverse String 0347.Top-K-Frequent-Elements 347. Top K Frequent Elements 0354.Russian-Doll-Envelopes 0354. Russian Doll Envelope 0380.Insert-Delete-GetRandom-O1 380. Insert Delete GetRandom O(1) 0381.Insert-Delete-GetRandom-O1-Duplicates-allowed 381.Insert Delete GetRandom O(1) Duplicates allowed 0409.Longest-Palindrome 0409. Longest Palindrome 0412.Fizz-Buzz 412. Fizz Buzz 0438.Find-All-Anagrams-in-a-String 0438.Find All Anagrams in a String 0509.Fibonacci-Number 0509.Fibonacci Number 0516.Longest-Palindromic-Subsequence 516. Longest Palindromic Subsequence 0543.Diameter-of-Binary-Tree 0543. Diameter of Binary Tree 0567.Permutation-in-String 0567.Permutation in String 0693.Binary-Number-with-Alternating-Bits 0693.Binary Number with Alternating Bits 0695.Max-Area-of-Island 0695.Max Area of Island 0703.Kth-Largest-Element-in-a-Stream 0703. Kth Largest Element in a Stream 0704.Binary-Search 0704.Binary Search 0721.Accounts-Merge 0721.Accounts Merge 0733.Flood-Fill 0733.Flood Fill 0746.Min-Cost-Climbing-Stairs 746. Min Cost Climbing Stairs 0752.Open-the-Lock 0752.Open the Lock 0876.Middle-of-the-Linked-List 0876.Middle of the Linked List 1046.Last-Stone-Weight 1046. Last Stone Weight 1143.Longest-Common-Subsequence 1143.Longest Common Subsequence 1195.Fizz-Buzz-Multithreaded 1195. Fizz Buzz Multithreaded Structures Heap Golang Container Heap Template CHANGELOG Content Tags ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:14:52 "},"tags.html":{"url":"tags.html","title":"Tags","keywords":"","body":"Tags ยฉ Kimi Tsai all right reserved. ย ย ย ย ย ย ย ย ย ย  Updated : 2024-03-24 07:13:39 Algorithm A1B2C3: Two Go Routine Print A1B2C3....Z26 Golang A1B2C3: Two Go Routine Print A1B2C3....Z26 Intersection Of Two Sorted Arrays Using In Place Approach Search Graph In Golang Weighted Edit Distance 0072. Edit Distance A1B2C3 A1B2C3: Two Go Routine Print A1B2C3....Z26 Interview Find Target Last Index Algorithms Find Target Last Index Intersection Of Two Sorted Arrays Using In Place Approach Search Graph In Golang Go Find Target Last Index Bank Requests Binary Gap Cyclic Rotation NUM.LEETCODETITLE 0002.Add Two Numbers 0003.Longest Substring Without Repeating Characters 0005. Longest Palindromic Substring 0015. 3Sum 0019. Remove Nth Node From End of List 0020. Valid Parentheses 0021. Merge Two Sorted Lists 0028. Find the Index of the First Occurrence in a String 0049.Group Anagrams 0053.Maximum Subarray 0070.Climbing Stairs 0078. Subsets 100. Same Tree 0104.Maximum Depth of Binary Tree 105. Construct Binary Tree from Preorder and Inorder Traversal 110. Balanced Binary Tree 0121.Best Time to Buy and Sell Stock 0125. Valid Palindrome 128. Longest Consecutive Sequence 138. Copy List with Random Pointer 143. Reorder List 0167.Two Sum II Input Array Is Sorted 206. Reverse Linked List 0215. Kth Largest Element in an Array 0217.Contains-Duplicate 226. Invert Binary Tree 238. Product of Array Except Self 0242.Valid-Anagram 0283. Move Zeroes 0322.Coin Change 347. Top K Frequent Elements 380. Insert Delete GetRandom O(1) 381.Insert Delete GetRandom O(1) Duplicates allowed 412. Fizz Buzz 0543. Diameter of Binary Tree 0695.Max Area of Island 0703. Kth Largest Element in a Stream 0733.Flood Fill 746. Min Cost Climbing Stairs 1046. Last Stone Weight 1195. Fizz Buzz Multithreaded Golang Container Heap Easy Find Target Last Index 0001.Two Sum 0020. Valid Parentheses 0027.Remove Element 0028. Find the Index of the First Occurrence in a String 0035.Search Insert Position 0070.Climbing Stairs 0088.Merge Sorted Array 100. Same Tree 0104.Maximum Depth of Binary Tree 110. Balanced Binary Tree 0121.Best Time to Buy and Sell Stock 0125. Valid Palindrome 0141.Linked List Cycle 0203.Remove Linked List Elements 206. Reverse Linked List 0217.Contains-Duplicate 226. Invert Binary Tree 0242.Valid-Anagram 0283. Move Zeroes 0344.Reverse String 0409. Longest Palindrome 412. Fizz Buzz 0509.Fibonacci Number 0543. Diameter of Binary Tree 0703. Kth Largest Element in a Stream 0704.Binary Search 0721.Accounts Merge 0733.Flood Fill 746. Min Cost Climbing Stairs 0876.Middle of the Linked List 1046. Last Stone Weight Find Target Last Index Find Target Last Index Right Bound Find Target Last Index Left Bound Find Target Last Index Intersection Intersection Of Two Sorted Arrays Using In Place Approach Search Graph Search Graph In Golang BFS Search Graph In Golang 226. Invert Binary Tree 0695.Max Area of Island 0733.Flood Fill WeightedEditDistance Weighted Edit Distance Dynamic Programming Weighted Edit Distance 0053.Maximum Subarray 0072. Edit Distance 0300.Longest Increasing Subsequence 0322.Coin Change 0354. Russian Doll Envelope 0509.Fibonacci Number 516. Longest Palindromic Subsequence 1143.Longest Common Subsequence CodeSignal Bank Requests Bank Requests Bank Requests Codility Binary Gap Cyclic Rotation Iterations Binary Gap Painless Binary Gap Cyclic Rotation Bitwise Manipulation Binary Gap Array Cyclic Rotation 0003.Longest Substring Without Repeating Characters 0015. 3Sum 0027.Remove Element 0035.Search Insert Position 0053.Maximum Subarray 0059.Spiral Matrix II 0088.Merge Sorted Array 105. Construct Binary Tree from Preorder and Inorder Traversal 128. Longest Consecutive Sequence 0167.Two Sum II Input Array Is Sorted 0217.Contains-Duplicate 238. Product of Array Except Self 380. Insert Delete GetRandom O(1) 381.Insert Delete GetRandom O(1) Duplicates allowed Multiple Pointers Cyclic Rotation LeetCode NUM.LEETCODETITLE 0002.Add Two Numbers 0003.Longest Substring Without Repeating Characters 0005. Longest Palindromic Substring 0015. 3Sum 0019. Remove Nth Node From End of List 0020. Valid Parentheses 0021. Merge Two Sorted Lists 0028. Find the Index of the First Occurrence in a String 0049.Group Anagrams 0053.Maximum Subarray 0070.Climbing Stairs 0078. Subsets 100. Same Tree 0104.Maximum Depth of Binary Tree 105. Construct Binary Tree from Preorder and Inorder Traversal 110. Balanced Binary Tree 0121.Best Time to Buy and Sell Stock 0125. Valid Palindrome 128. Longest Consecutive Sequence 138. Copy List with Random Pointer 143. Reorder List 0167.Two Sum II Input Array Is Sorted 206. Reverse Linked List 0215. Kth Largest Element in an Array 0217.Contains-Duplicate 226. Invert Binary Tree 238. Product of Array Except Self 0242.Valid-Anagram 0283. Move Zeroes 0322.Coin Change 347. Top K Frequent Elements 380. Insert Delete GetRandom O(1) 381.Insert Delete GetRandom O(1) Duplicates allowed 412. Fizz Buzz 0543. Diameter of Binary Tree 0695.Max Area of Island 0703. Kth Largest Element in a Stream 0733.Flood Fill 746. Min Cost Climbing Stairs 1046. Last Stone Weight 1195. Fizz Buzz Multithreaded Easy/Medium/Hard NUM.LEETCODETITLE 0021. Merge Two Sorted Lists LEETCODETITLE NUM.LEETCODETITLE 0104.Maximum Depth of Binary Tree Medium 0002.Add Two Numbers 0003.Longest Substring Without Repeating Characters 0005. Longest Palindromic Substring 0015. 3Sum 0019. Remove Nth Node From End of List 0046.Permutations 0049.Group Anagrams 0053.Maximum Subarray 0059.Spiral Matrix II 0075.Sort Colors 0078. Subsets 0094.Binary Tree Inorder Traversal 105. Construct Binary Tree from Preorder and Inorder Traversal 128. Longest Consecutive Sequence 138. Copy List with Random Pointer 0142.Linked List Cycle II 0167.Two Sum II Input Array Is Sorted 0209. Minimum Size Subarray Sum 0215. Kth Largest Element in an Array 238. Product of Array Except Self 0300.Longest Increasing Subsequence 0310.Minimum Height Trees 0322.Coin Change 347. Top K Frequent Elements 380. Insert Delete GetRandom O(1) 0438.Find All Anagrams in a String 516. Longest Palindromic Subsequence 0567.Permutation in String 0693.Binary Number with Alternating Bits 0695.Max Area of Island 0752.Open the Lock 1143.Longest Common Subsequence 1195. Fizz Buzz Multithreaded Add Two Numbers 0002.Add Two Numbers Linked List 0002.Add Two Numbers 0019. Remove Nth Node From End of List 0141.Linked List Cycle 0142.Linked List Cycle II 143. Reorder List 0203.Remove Linked List Elements 0876.Middle of the Linked List Math 0002.Add Two Numbers Recursion 0002.Add Two Numbers 143. Reorder List Amazon 0002.Add Two Numbers 0005. Longest Palindromic Substring 0019. Remove Nth Node From End of List 128. Longest Consecutive Sequence 138. Copy List with Random Pointer 143. Reorder List Apple 0002.Add Two Numbers 412. Fizz Buzz Facebook 0002.Add Two Numbers 0005. Longest Palindromic Substring 0019. Remove Nth Node From End of List 138. Copy List with Random Pointer 143. Reorder List 412. Fizz Buzz Microsoft 0002.Add Two Numbers 0005. Longest Palindromic Substring 0019. Remove Nth Node From End of List 128. Longest Consecutive Sequence 138. Copy List with Random Pointer 143. Reorder List 412. Fizz Buzz Bloomberg 0002.Add Two Numbers 0019. Remove Nth Node From End of List 138. Copy List with Random Pointer 143. Reorder List Longest Substring Without Repeating Characters 0003.Longest Substring Without Repeating Characters Sliding Window 0003.Longest Substring Without Repeating Characters 0209. Minimum Size Subarray Sum 0438.Find All Anagrams in a String 0567.Permutation in String DP 0005. Longest Palindromic Substring 0070.Climbing Stairs 0121.Best Time to Buy and Sell Stock Google 0005. Longest Palindromic Substring 0019. Remove Nth Node From End of List 128. Longest Consecutive Sequence 138. Copy List with Random Pointer Adobe 0005. Longest Palindromic Substring 128. Longest Consecutive Sequence 143. Reorder List 3Sum 0015. 3Sum Two Pointers 0015. 3Sum 0019. Remove Nth Node From End of List 0028. Find the Index of the First Occurrence in a String 0141.Linked List Cycle 0142.Linked List Cycle II 143. Reorder List 0167.Two Sum II Input Array Is Sorted 0344.Reverse String 0876.Middle of the Linked List Sorting 0015. 3Sum 0215. Kth Largest Element in an Array Valid Parentheses 0020. Valid Parentheses Merge Two Sorted Lists 0021. Merge Two Sorted Lists Find the Index of the First Occurrence in a String 0028. Find the Index of the First Occurrence in a String String 0028. Find the Index of the First Occurrence in a String 0409. Longest Palindrome String Matching 0028. Find the Index of the First Occurrence in a String Backtracking 0046.Permutations Group Anagrams 0049.Group Anagrams Blind75 0053.Maximum Subarray 0121.Best Time to Buy and Sell Stock 0217.Contains-Duplicate 238. Product of Array Except Self Climbing Stairs 0070.Climbing Stairs Hard 0072. Edit Distance 0354. Russian Doll Envelope 381.Insert Delete GetRandom O(1) Duplicates allowed Edit Distance 0072. Edit Distance Sort 0075.Sort Colors Subsets 0078. Subsets Stack 0094.Binary Tree Inorder Traversal 143. Reorder List Same Tree 100. Same Tree Tree 100. Same Tree 105. Construct Binary Tree from Preorder and Inorder Traversal Construct Binary Tree from Preorder and Inorder Traversal 105. Construct Binary Tree from Preorder and Inorder Traversal Hash Table 105. Construct Binary Tree from Preorder and Inorder Traversal 128. Longest Consecutive Sequence Divide and Conquer 105. Construct Binary Tree from Preorder and Inorder Traversal Binary Tree 105. Construct Binary Tree from Preorder and Inorder Traversal Balanced Binary Tree 110. Balanced Binary Tree DFS 110. Balanced Binary Tree 0543. Diameter of Binary Tree 0695.Max Area of Island 0733.Flood Fill Slide Windows 0121.Best Time to Buy and Sell Stock Best Time to Buy and Sell Stock 0121.Best Time to Buy and Sell Stock array 0121.Best Time to Buy and Sell Stock Valid Palindrome 0125. Valid Palindrome Longest Consecutive Sequence 128. Longest Consecutive Sequence Union Find 128. Longest Consecutive Sequence 0721.Accounts Merge Spotify 128. Longest Consecutive Sequence Copy List with Random Pointer 138. Copy List with Random Pointer /Medium 143. Reorder List 143. Reorder List 143. Reorder List Two Sum II Input Array Is Sorted 0167.Two Sum II Input Array Is Sorted Binary Search 0167.Two Sum II Input Array Is Sorted 0300.Longest Increasing Subsequence 0354. Russian Doll Envelope 0704.Binary Search Reverse Linked List 206. Reverse Linked List Kth Largest Element in an Array 0215. Kth Largest Element in an Array Heap 0215. Kth Largest Element in an Array 0703. Kth Largest Element in a Stream 1046. Last Stone Weight Priority Queue 0215. Kth Largest Element in an Array 0703. Kth Largest Element in a Stream 1046. Last Stone Weight Contains Duplicate 0217.Contains-Duplicate Invert Binary Tree 226. Invert Binary Tree Product of Array Except Self 238. Product of Array Except Self Prefix Sum 238. Product of Array Except Self Valid Anagram 0242.Valid-Anagram Move Zeroes 0283. Move Zeroes Patience Sorting 0300.Longest Increasing Subsequence Breadth First Search 0310.Minimum Height Trees 0752.Open the Lock Coin Change 0322.Coin Change Top K Frequent Elements 347. Top K Frequent Elements heap 347. Top K Frequent Elements Insert Delete GetRandom O(1) 380. Insert Delete GetRandom O(1) Hash 380. Insert Delete GetRandom O(1) 381.Insert Delete GetRandom O(1) Duplicates allowed Insert Delete GetRandom O(1) Duplicates allowed 381.Insert Delete GetRandom O(1) Duplicates allowed Fizz Buzz 412. Fizz Buzz string 412. Fizz Buzz math 412. Fizz Buzz Diameter of Binary Tree 0543. Diameter of Binary Tree Bit Manipulation 0693.Binary Number with Alternating Bits Max Area of Island 0695.Max Area of Island Array & String 0695.Max Area of Island Matrix 0695.Max Area of Island Kth Largest Element in a Stream 0703. Kth Largest Element in a Stream Flood Fill 0733.Flood Fill Min Cost Climbing Stairs 746. Min Cost Climbing Stairs Last Stone Weight 1046. Last Stone Weight Fizz Buzz Multithreaded 1195. Fizz Buzz Multithreaded Concurrency 1195. Fizz Buzz Multithreaded container/heap Golang Container Heap "}} \ No newline at end of file diff --git a/sitemap.xml b/sitemap.xml new file mode 100644 index 000000000..edd2f6b81 --- /dev/null +++ b/sitemap.xml @@ -0,0 +1,126 @@ + + + https://kimi0230.github.io/LeetcodeGolang/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Algorithms/A1B2C3/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Algorithms/Find_Target_Last_Index/findtargetlastindex.html weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Algorithms/Intersection-of-Two-Sorted-Arrays-using-In-Place-Approach/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Algorithms/SearchGraph/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Algorithms/WeightedEditDistance/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/CodeSignal/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/CodeSignal/Bank-Requests/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0001.Iterations/Binary-Gap/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0002.Array/CyclicRotation/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0002.Array/OddOccurrencesInArray/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0003.Time-Complexity/FrogJmp/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0003.Time-Complexity/PermMissingElem/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0003.Time-Complexity/TapeEquilibrium/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0004.Counting-Elements/FrogRiverOne/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0004.Counting-Elements/MaxCounters/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0004.Counting-Elements/MissingInteger/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0004.Counting-Elements/PermCheck/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0005.Prefix-Sums/CountDiv/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0005.Prefix-Sums/GenomicRangeQuery/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0005.Prefix-Sums/MinAvgTwoSlice/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0005.Prefix-Sums/PassingCars/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0006.Sorting/Distinct/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0006.Sorting/MaxProductOfThree/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0006.Sorting/NumberOfDiscIntersections/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0006.Sorting/Triangle/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0007.Stacks-and-Queues/Brackets/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0007.Stacks-and-Queues/Fish/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0007.Stacks-and-Queues/Nesting/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0007.Stacks-and-Queues/StoneWall/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0008.Leader/Dominator/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0008.Leader/EquiLeader/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0009.Maximum-Slice-Problem/MaxDoubleSliceSum/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0009.Maximum-Slice-Problem/MaxProfit/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0009.Maximum-Slice-Problem/MaxSliceSum/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0010.Prime-And-Composite-Numbers/CountFactors/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0010.Prime-And-Composite-Numbers/Flags/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0010.Prime-And-Composite-Numbers/MinPerimeterRectangle/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0010.Prime-And-Composite-Numbers/Peaks/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountNonDivisible/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0011.Sieve-of-Eratosthenes/CountSemiprimes/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0012.Euclidean-Algorithm/ChocolatesByNumbers/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0012.Euclidean-Algorithm/CommonPrimeDivisors/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0013.Fibonacci-Numbers/FibFrog/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Codility/Lesson/0015.Caterpillar-Method/AbsDistinct/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/GeeksforGeeks/SortingAlgorithms/0031.Find-Minimum-Difference-Between-Any-Two-Elements/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0000.xxxx/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0001.Two-Sum/Merging-2-Packages/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0001.Two-Sum/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0002.Add-Two-Numbers/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0003.Longest-Substring-Without-Repeating-Characters/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0005.Longest-Palindromic-Substring/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0015.3Sum/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0019.Remove-Nth-Node-From-End-of-List/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0020.Valid-Parentheses/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0021.Merge-Two-Sorted-Lists/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0027.Remove-Element/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0028.Find-the-Index-of-the-First-Occurrence-in-a-String/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0035.Search-Insert-Position/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0046.Permutations/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0049.Group-Anagrams/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0053.Maximum-Subarray/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0059.Spiral-Matrix-II/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0070.Climbing-Stairs/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0072.Edit-Distance/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0075.Sort-Colors/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0078.Subsets/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0088.Merge-Sorted-Array/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0094.Binary-Tree-Inorder-Traversal/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0100.Same-Tree/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0104.Maximum-Depth-of-Binary-Tree/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0105.Construct-Binary-Tree-from-Preorder-and-Inorder-Traversal/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0110.Balanced-Binary-Tree/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0121.Best-Time-to-Buy-and-Sell-Stock/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0125.Valid-Palindrome/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0128.Longest-Consecutive-Sequence/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0138.Copy-List-with-Random-Pointer/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0141.Linked-List-Cycle/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0142.Linked-List-CycleII/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0143.Reorder-List/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0167.Two-Sum-II-Input-Array-Is-Sorted/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0203.Remove-Linked-List-Elements/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0206.Reverse-Linked-List/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0209.Minimum-Size-Subarray-Sum/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0215.Kth-Largest-Element-in-an-Array/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0217.Contains-Duplicate/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0226.Invert-Binary-Tree/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0238.Product-of-Array-Except-Self/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0242.Valid-Anagram/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0283.Move-Zeroes/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0300.Longest-Increasing-Subsequence/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0310.Minimum-Height-Trees/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0322.Coin-Change/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0344.Reverse-String/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0347.Top-K-Frequent-Elements/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0354.Russian-Doll-Envelopes/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0380.Insert-Delete-GetRandom-O1/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0381.Insert-Delete-GetRandom-O1-Duplicates-allowed/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0409.Longest-Palindrome/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0412.Fizz-Buzz/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0438.Find-All-Anagrams-in-a-String/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0509.Fibonacci-Number/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0516.Longest-Palindromic-Subsequence/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0543.Diameter-of-Binary-Tree/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0567.Permutation-in-String/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0693.Binary-Number-with-Alternating-Bits/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0695.Max-Area-of-Island/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0703.Kth-Largest-Element-in-a-Stream/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0704.Binary-Search/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0721.Accounts-Merge/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0733.Flood-Fill/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0746.Min-Cost-Climbing-Stairs/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0752.Open-the-Lock/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/0876.Middle-of-the-Linked-List/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/1046.Last-Stone-Weight/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/1143.Longest-Common-Subsequence/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Leetcode/1195.Fizz-Buzz-Multithreaded/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/structures/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/structures/heap/index.en.html weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/template/ weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/CHANGELOG.html weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/Content.html weekly 0.5 + https://kimi0230.github.io/LeetcodeGolang/tags.html weekly 0.5 + \ No newline at end of file diff --git a/structures/Heap.go b/structures/Heap.go new file mode 100644 index 000000000..2910773b4 --- /dev/null +++ b/structures/Heap.go @@ -0,0 +1,30 @@ +package structures + +// intHeap ๅฎž็Žฐไบ†ๆœ€ๅฐๅ † heap ็š„ๆŽฅๅฃ +type intHeap []int + +func (h intHeap) Len() int { + return len(h) +} + +func (h intHeap) Less(i, j int) bool { + return h[i] < h[j] +} + +func (h intHeap) Swap(i, j int) { + h[i], h[j] = h[j], h[i] +} + +func (h *intHeap) Push(x interface{}) { + // Push ไฝฟ็”จ *h๏ผŒๆ˜ฏๅ› ไธบ + // Push ๅขžๅŠ ไบ† h ็š„้•ฟๅบฆ + *h = append(*h, x.(int)) +} + +func (h *intHeap) Pop() interface{} { + // Pop ไฝฟ็”จ *h ๏ผŒๆ˜ฏๅ› ไธบ + // Pop ๅ‡็Ÿญไบ† h ็š„้•ฟๅบฆ + res := (*h)[len(*h)-1] + *h = (*h)[:len(*h)-1] + return res +} diff --git a/structures/Heap_test.go b/structures/Heap_test.go new file mode 100644 index 000000000..8e6a30c40 --- /dev/null +++ b/structures/Heap_test.go @@ -0,0 +1,30 @@ +package structures + +import ( + "container/heap" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_intHeap(t *testing.T) { + ast := assert.New(t) + + ih := new(intHeap) + heap.Init(ih) + + heap.Push(ih, 1) + heap.Pop(ih) + + begin, end := 0, 10 + for i := begin; i < end; i++ { + heap.Push(ih, i) + ast.Equal(0, (*ih)[0], "ๆ’ๅ…ฅ %d ๅŽ็š„ๆœ€ๅฐๅ€ผๅดๆ˜ฏ %d๏ผŒih=%v", i, (*ih)[0], (*ih)) + } + + for i := begin; i < end; i++ { + fmt.Println(i, *ih) + ast.Equal(i, heap.Pop(ih), "Pop ๅŽ ih=%v", (*ih)) + } +} diff --git a/structures/Interval.go b/structures/Interval.go new file mode 100644 index 000000000..bed1432e8 --- /dev/null +++ b/structures/Interval.go @@ -0,0 +1,53 @@ +package structures + +// Interval ๆไพ›ๅŒบ้—ด่กจ็คบ +type Interval struct { + Start int + End int +} + +// Interval2Ints ๆŠŠ Interval ่ฝฌๆขๆˆ ๆ•ดๅž‹ๅˆ‡็‰‡ +func Interval2Ints(i Interval) []int { + return []int{i.Start, i.End} +} + +// IntervalSlice2Intss ๆŠŠ []Interval ่ฝฌๆขๆˆ [][]int +func IntervalSlice2Intss(is []Interval) [][]int { + res := make([][]int, 0, len(is)) + for i := range is { + res = append(res, Interval2Ints(is[i])) + } + return res +} + +// Intss2IntervalSlice ๆŠŠ [][]int ่ฝฌๆขๆˆ []Interval +func Intss2IntervalSlice(intss [][]int) []Interval { + res := make([]Interval, 0, len(intss)) + for _, ints := range intss { + res = append(res, Interval{Start: ints[0], End: ints[1]}) + } + return res +} + +// QuickSort define +func QuickSort(a []Interval, lo, hi int) { + if lo >= hi { + return + } + p := partitionSort(a, lo, hi) + QuickSort(a, lo, p-1) + QuickSort(a, p+1, hi) +} + +func partitionSort(a []Interval, lo, hi int) int { + pivot := a[hi] + i := lo - 1 + for j := lo; j < hi; j++ { + if (a[j].Start < pivot.Start) || (a[j].Start == pivot.Start && a[j].End < pivot.End) { + i++ + a[j], a[i] = a[i], a[j] + } + } + a[i+1], a[hi] = a[hi], a[i+1] + return i + 1 +} diff --git a/structures/Interval_test.go b/structures/Interval_test.go new file mode 100644 index 000000000..dd36e40a5 --- /dev/null +++ b/structures/Interval_test.go @@ -0,0 +1,59 @@ +package structures + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_Interval2Ints(t *testing.T) { + ast := assert.New(t) + + actual := Interval2Ints(Interval{Start: 1, End: 2}) + expected := []int{1, 2} + ast.Equal(expected, actual) +} + +func Test_IntervalSlice2Intss(t *testing.T) { + ast := assert.New(t) + + actual := IntervalSlice2Intss( + []Interval{ + { + Start: 1, + End: 2, + }, + { + Start: 3, + End: 4, + }, + }, + ) + expected := [][]int{ + {1, 2}, + {3, 4}, + } + + ast.Equal(expected, actual) +} +func Test_Intss2IntervalSlice(t *testing.T) { + ast := assert.New(t) + + expected := []Interval{ + { + Start: 1, + End: 2, + }, + { + Start: 3, + End: 4, + }, + } + actual := Intss2IntervalSlice([][]int{ + {1, 2}, + {3, 4}, + }, + ) + + ast.Equal(expected, actual) +} diff --git a/structures/ListNode.go b/structures/ListNode.go new file mode 100644 index 000000000..9f3dc9ed4 --- /dev/null +++ b/structures/ListNode.go @@ -0,0 +1,82 @@ +package structures + +import ( + "fmt" +) + +// ListNode ๆ˜ฏ้“พๆŽฅ่Š‚็‚น +// ่ฟ™ไธชไธ่ƒฝๅคๅˆถๅˆฐ*_test.goๆ–‡ไปถไธญใ€‚ไผšๅฏผ่‡ดTravisๅคฑ่ดฅ +type ListNode struct { + Val int + Next *ListNode +} + +// List2Ints convert List to []int +func List2Ints(head *ListNode) []int { + // ้“พๆกๆทฑๅบฆ้™ๅˆถ๏ผŒ้“พๆกๆทฑๅบฆ่ถ…ๅ‡บๆญค้™ๅˆถ๏ผŒไผš panic + limit := 100 + + times := 0 + + res := []int{} + for head != nil { + times++ + if times > limit { + msg := fmt.Sprintf("้“พๆกๆทฑๅบฆ่ถ…่ฟ‡%d๏ผŒๅฏ่ƒฝๅ‡บ็Žฐ็Žฏ็Šถ้“พๆกใ€‚่ฏทๆฃ€ๆŸฅ้”™่ฏฏ๏ผŒๆˆ–่€…ๆ”พๅฎฝ l2s ๅ‡ฝๆ•ฐไธญ limit ็š„้™ๅˆถใ€‚", limit) + panic(msg) + } + + res = append(res, head.Val) + head = head.Next + } + + return res +} + +// Ints2List convert []int to List +func Ints2List(nums []int) *ListNode { + if len(nums) == 0 { + return nil + } + + l := &ListNode{} + t := l + for _, v := range nums { + t.Next = &ListNode{Val: v} + t = t.Next + } + return l.Next +} + +// GetNodeWith returns the first node with val +func (l *ListNode) GetNodeWith(val int) *ListNode { + res := l + for res != nil { + if res.Val == val { + break + } + res = res.Next + } + return res +} + +// Ints2ListWithCycle returns a list whose tail point to pos-indexed node +// head's index is 0 +// if pos = -1, no cycle +func Ints2ListWithCycle(nums []int, pos int) *ListNode { + head := Ints2List(nums) + if pos == -1 { + return head + } + c := head + for pos > 0 { + c = c.Next + pos-- + } + tail := c + for tail.Next != nil { + tail = tail.Next + } + tail.Next = c + return head +} diff --git a/structures/ListNode_test.go b/structures/ListNode_test.go new file mode 100644 index 000000000..ed1df4f61 --- /dev/null +++ b/structures/ListNode_test.go @@ -0,0 +1,68 @@ +package structures + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_l2s(t *testing.T) { + ast := assert.New(t) + ast.Equal([]int{}, List2Ints(nil), "่พ“ๅ…ฅnil๏ผŒๆฒกๆœ‰่ฟ”ๅ›ž[]int{}") + + one2three := &ListNode{ + Val: 1, + Next: &ListNode{ + Val: 2, + Next: &ListNode{ + Val: 3, + }, + }, + } + ast.Equal([]int{1, 2, 3}, List2Ints(one2three), "ๆฒกๆœ‰ๆˆๅŠŸๅœฐ่ฝฌๆขๆˆ[]int") + + limit := 100 + overLimitList := Ints2List(make([]int, limit+1)) + ast.Panics(func() { List2Ints(overLimitList) }, "่ฝฌๆขๆทฑๅบฆ่ถ…่ฟ‡ %d ้™ๅˆถ็š„้“พๆก๏ผŒๆฒกๆœ‰ panic", limit) +} + +func Test_s2l(t *testing.T) { + ast := assert.New(t) + ast.Nil(Ints2List([]int{}), "่พ“ๅ…ฅ[]int{}๏ผŒๆฒกๆœ‰่ฟ”ๅ›žnil") + + ln := Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}) + i := 1 + for ln != nil { + ast.Equal(i, ln.Val, "ๅฏนๅบ”็š„ๅ€ผไธๅฏน") + ln = ln.Next + i++ + } +} + +func Test_getNodeWith(t *testing.T) { + ast := assert.New(t) + // + ln := Ints2List([]int{1, 2, 3, 4, 5, 6, 7, 8, 9}) + val := 10 + node := &ListNode{ + Val: val, + } + tail := ln + for tail.Next != nil { + tail = tail.Next + } + tail.Next = node + expected := node + actual := ln.GetNodeWith(val) + ast.Equal(expected, actual) +} + +func Test_Ints2ListWithCycle(t *testing.T) { + ast := assert.New(t) + ints := []int{1, 2, 3} + l := Ints2ListWithCycle(ints, -1) + ast.Equal(ints, List2Ints(l)) + + l = Ints2ListWithCycle(ints, 1) + ast.Panics(func() { List2Ints(l) }) +} diff --git a/structures/NestedInteger.go b/structures/NestedInteger.go new file mode 100644 index 000000000..0a944f39c --- /dev/null +++ b/structures/NestedInteger.go @@ -0,0 +1,37 @@ +package structures + +// NestedInteger is the interface that allows for creating nested lists. +// You should not implement it, or speculate about its implementation +type NestedInteger struct { + Num int + Ns []*NestedInteger +} + +// IsInteger Return true if this NestedInteger holds a single integer, rather than a nested list. +func (n NestedInteger) IsInteger() bool { + return n.Ns == nil +} + +// GetInteger Return the single integer that this NestedInteger holds, if it holds a single integer +// The result is undefined if this NestedInteger holds a nested list +// So before calling this method, you should have a check +func (n NestedInteger) GetInteger() int { + return n.Num +} + +// SetInteger Set this NestedInteger to hold a single integer. +func (n *NestedInteger) SetInteger(value int) { + n.Num = value +} + +// Add Set this NestedInteger to hold a nested list and adds a nested integer to it. +func (n *NestedInteger) Add(elem NestedInteger) { + n.Ns = append(n.Ns, &elem) +} + +// GetList Return the nested list that this NestedInteger holds, if it holds a nested list +// The list length is zero if this NestedInteger holds a single integer +// You can access NestedInteger's List element directly if you want to modify it +func (n NestedInteger) GetList() []*NestedInteger { + return n.Ns +} diff --git a/structures/NestedInterger_test.go b/structures/NestedInterger_test.go new file mode 100644 index 000000000..bf1727b5e --- /dev/null +++ b/structures/NestedInterger_test.go @@ -0,0 +1,30 @@ +package structures + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_NestedInteger(t *testing.T) { + ast := assert.New(t) + + n := NestedInteger{} + + ast.True(n.IsInteger()) + + n.SetInteger(1) + ast.Equal(1, n.GetInteger()) + + elem := NestedInteger{Num: 1} + + expected := NestedInteger{ + Num: 1, + Ns: []*NestedInteger{&elem}, + } + n.Add(elem) + + ast.Equal(expected, n) + + ast.Equal(expected.Ns, n.GetList()) +} diff --git a/structures/Point.go b/structures/Point.go new file mode 100644 index 000000000..4e5e4c7e5 --- /dev/null +++ b/structures/Point.go @@ -0,0 +1,27 @@ +package structures + +// Point ๅฎšไน‰ไบ†ไธ€ไธชไบŒ็ปดๅๆ ‡็‚น +type Point struct { + X, Y int +} + +// Intss2Points ๆŠŠ [][]int ่ฝฌๆขๆˆ []Point +func Intss2Points(points [][]int) []Point { + res := make([]Point, len(points)) + for i, p := range points { + res[i] = Point{ + X: p[0], + Y: p[1], + } + } + return res +} + +// Points2Intss ๆŠŠ []Point ่ฝฌๆขๆˆใ€€[][]int +func Points2Intss(points []Point) [][]int { + res := make([][]int, len(points)) + for i, p := range points { + res[i] = []int{p.X, p.Y} + } + return res +} diff --git a/structures/Point_test.go b/structures/Point_test.go new file mode 100644 index 000000000..48b6dc1ce --- /dev/null +++ b/structures/Point_test.go @@ -0,0 +1,78 @@ +package structures + +import ( + "reflect" + "testing" +) + +func Test_Intss2Points(t *testing.T) { + type args struct { + points [][]int + } + tests := []struct { + name string + args args + want []Point + }{ + { + "ๆต‹่ฏ• [][]int ่ฝฌๆขๆˆ []Point ", + args{ + [][]int{ + {1, 0}, + {2, 0}, + {3, 0}, + {4, 0}, + {5, 0}, + }, + }, + []Point{ + {X: 1, Y: 0}, + {X: 2, Y: 0}, + {X: 3, Y: 0}, + {X: 4, Y: 0}, + {X: 5, Y: 0}, + }, + }, + } + for _, tt := range tests { + if got := Intss2Points(tt.args.points); !reflect.DeepEqual(got, tt.want) { + t.Errorf("%q. intss2Points() = %v, want %v", tt.name, got, tt.want) + } + } +} + +func Test_Points2Intss(t *testing.T) { + type args struct { + points []Point + } + tests := []struct { + name string + args args + want [][]int + }{ + { + "ๆต‹่ฏ• [][]int ่ฝฌๆขๆˆ []Point ", + args{ + []Point{ + {X: 1, Y: 0}, + {X: 2, Y: 0}, + {X: 3, Y: 0}, + {X: 4, Y: 0}, + {X: 5, Y: 0}, + }, + }, + [][]int{ + {1, 0}, + {2, 0}, + {3, 0}, + {4, 0}, + {5, 0}, + }, + }, + } + for _, tt := range tests { + if got := Points2Intss(tt.args.points); !reflect.DeepEqual(got, tt.want) { + t.Errorf("%q. Points2Intss() = %v, want %v", tt.name, got, tt.want) + } + } +} diff --git a/structures/PriorityQueue.go b/structures/PriorityQueue.go new file mode 100644 index 000000000..01677463a --- /dev/null +++ b/structures/PriorityQueue.go @@ -0,0 +1,54 @@ +package structures + +// This example demonstrates a priority queue built using the heap interface. + +import ( + "container/heap" +) + +// entry ๆ˜ฏ priorityQueue ไธญ็š„ๅ…ƒ็ด  +type entry struct { + key string + priority int + // index ๆ˜ฏ entry ๅœจ heap ไธญ็š„็ดขๅผ•ๅท + // entry ๅŠ ๅ…ฅ Priority Queue ๅŽ๏ผŒ Priority ไผšๅ˜ๅŒ–ๆ—ถ๏ผŒๅพˆๆœ‰็”จ + // ๅฆ‚ๆžœ entry.priority ไธ€็›ดไธๅ˜็š„่ฏ๏ผŒๅฏไปฅๅˆ ้™ค index + index int +} + +// PQ implements heap.Interface and holds entries. +type PQ []*entry + +func (pq PQ) Len() int { return len(pq) } + +func (pq PQ) Less(i, j int) bool { + return pq[i].priority < pq[j].priority +} + +func (pq PQ) Swap(i, j int) { + pq[i], pq[j] = pq[j], pq[i] + pq[i].index = i + pq[j].index = j +} + +// Push ๅพ€ pq ไธญๆ”พ entry +func (pq *PQ) Push(x interface{}) { + temp := x.(*entry) + temp.index = len(*pq) + *pq = append(*pq, temp) +} + +// Pop ไปŽ pq ไธญๅ–ๅ‡บๆœ€ไผ˜ๅ…ˆ็š„ entry +func (pq *PQ) Pop() interface{} { + temp := (*pq)[len(*pq)-1] + temp.index = -1 // for safety + *pq = (*pq)[0 : len(*pq)-1] + return temp +} + +// update modifies the priority and value of an entry in the queue. +func (pq *PQ) update(entry *entry, value string, priority int) { + entry.key = value + entry.priority = priority + heap.Fix(pq, entry.index) +} diff --git a/structures/PriorityQueue_test.go b/structures/PriorityQueue_test.go new file mode 100644 index 000000000..e171464bd --- /dev/null +++ b/structures/PriorityQueue_test.go @@ -0,0 +1,53 @@ +package structures + +import ( + "container/heap" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_priorityQueue(t *testing.T) { + ast := assert.New(t) + + // Some items and their priorities. + items := map[string]int{ + "banana": 2, "apple": 1, "pear": 3, + } + + // Create a priority queue, put the items in it, and + // establish the priority queue (heap) invariants. + pq := make(PQ, len(items)) + i := 0 + for value, priority := range items { + pq[i] = &entry{ + key: value, + priority: priority, + index: i, + } + i++ + } + heap.Init(&pq) + + // Insert a new item and then modify its priority. + it := &entry{ + key: "orange", + priority: 5, + } + heap.Push(&pq, it) + pq.update(it, it.key, 0) + + // Some items and their priorities. + expected := []string{ + "orange", + "apple", + "banana", + "pear", + } + + // Take the items out; they arrive in decreasing priority order. + for pq.Len() > 0 { + it := heap.Pop(&pq).(*entry) + ast.Equal(expected[it.priority], it.key) + } +} diff --git a/structures/Quadtree/Quadtree.go b/structures/Quadtree/Quadtree.go new file mode 100644 index 000000000..465039170 --- /dev/null +++ b/structures/Quadtree/Quadtree.go @@ -0,0 +1,153 @@ +package quadtree + +// ๅฎš็พฉไธ€ๅ€‹ไบŒ็ถญ้ปž็š„็ตๆง‹ +type Point struct { + X, Y float64 +} + +// ๅฎš็พฉไธ€ๅ€‹็Ÿฉๅฝข็ตๆง‹ +type Rect struct { + // ๅทฆไธŠ (X1,Y1) ; ๅณไธ‹ (X2,Y2) + X1, Y1, X2, Y2 float64 +} + +// ๅปบ็ซ‹ไธ€ๅ€‹ๆ–ฐ็š„็Ÿฉๅฝข +func NewRect(x1, y1, x2, y2 float64) Rect { + return Rect{X1: x1, Y1: y1, X2: x2, Y2: y2} +} + +// ่จˆ็ฎ—็Ÿฉๅฝข็š„ๅฏฌๅบฆ +func (r Rect) Width() float64 { + return r.X2 - r.X1 +} + +// ่จˆ็ฎ—็Ÿฉๅฝข็š„้ซ˜ๅบฆ +func (r Rect) Height() float64 { + return r.Y2 - r.Y1 +} + +// ๆชขๆŸฅ็Ÿฉๅฝขๆ˜ฏๅฆๅŒ…ๅซๆŸไธ€้ปž +func (r Rect) Contains(point Point) bool { + return point.X >= r.X1 && point.X <= r.X2 && point.Y >= r.Y1 && point.Y <= r.Y2 +} + +// ๆชขๆŸฅ็Ÿฉๅฝขๆ˜ฏๅฆ่ˆ‡ๅฆไธ€ๅ€‹็Ÿฉๅฝข็›ธไบค +func (r Rect) Intersects(other Rect) bool { + return r.X1 < other.X2 && r.X2 > other.X1 && r.Y1 < other.Y2 && r.Y2 > other.Y1 +} + +// ๅฎš็พฉๅ››ๅ‰ๆจน็ฏ€้ปž็ตๆง‹ +type QuadTreeNode struct { + Bounds Rect + Points []Point + NW, NE, SW, SE *QuadTreeNode +} + +// ๅ‰ตๅปบไธ€ๅ€‹ๆ–ฐ็š„ๅ››ๅ‰ๆจน็ฏ€้ปž +func NewQuadTreeNode(bounds Rect) *QuadTreeNode { + return &QuadTreeNode{ + Bounds: bounds, + Points: make([]Point, 0), + } +} + +// ๆ’ๅ…ฅไธ€ๅ€‹้ปžๅˆฐๅ››ๅ‰ๆจน +func (n *QuadTreeNode) Insert(point Point) { + if !n.Bounds.Contains(point) { + return + } + + if len(n.Points) < 4 { + n.Points = append(n.Points, point) + return + } + + if n.NW == nil { + n.Subdivide() + } + + n.NW.Insert(point) + n.NE.Insert(point) + n.SW.Insert(point) + n.SE.Insert(point) +} + +// ๅฐ‡็ฏ€้ปžๅˆ†็‚บๅ››ๅ€‹ๅญ็ต้ปž +// |NW|NE| +// |SW|SE| +func (n *QuadTreeNode) Subdivide() { + xMid := (n.Bounds.X1 + n.Bounds.X2) / 2 + yMid := (n.Bounds.Y1 + n.Bounds.Y2) / 2 + + n.NW = NewQuadTreeNode(Rect{n.Bounds.X1, n.Bounds.Y1, xMid, yMid}) + n.NE = NewQuadTreeNode(Rect{xMid, n.Bounds.Y1, n.Bounds.X2, yMid}) + n.SW = NewQuadTreeNode(Rect{n.Bounds.X1, yMid, xMid, n.Bounds.Y2}) + n.SE = NewQuadTreeNode(Rect{xMid, yMid, n.Bounds.X2, n.Bounds.Y2}) +} + +// ๅพž็ฏ€้ปžไธญๅˆ ้™คไธ€ๅ€‹้ปž +func (n *QuadTreeNode) Delete(point Point) { + if !n.Bounds.Contains(point) { + return + } + + for i, p := range n.Points { + if p == point { + // ๅพž็ฏ€้ปžไธญๅˆช้™ค้ปž + n.Points = append(n.Points[:i], n.Points[i+1:]...) + return + } + } + + if n.NW == nil { + return + } + + n.NW.Delete(point) + n.NE.Delete(point) + n.SW.Delete(point) + n.SE.Delete(point) +} + +type QueryContext struct { + Visited map[Point]bool +} + +func NewQueryContext() *QueryContext { + return &QueryContext{Visited: make(map[Point]bool)} +} + +// ๆŸฅ่ฉขไธ€ๅ€‹็ฏ„ๅœๅ†…็š„้ปž +func (n *QuadTreeNode) QueryRange(rangeRect Rect) []Point { + visited := NewQueryContext() + return n.queryRange(rangeRect, visited) +} + +// ๆŸฅ่ฉขไธ€ๅ€‹็ฏ„ๅœๅ†…็š„้ปž +func (n *QuadTreeNode) queryRange(rangeRect Rect, context *QueryContext) []Point { + result := make([]Point, 0) + + // ๅˆคๆ–ทๆœๅฐ‹็ฏ„ๅœ(range)ๆ˜ฏๅฆ่ˆ‡็•ถๅ‰้ ˜ๅŸŸๆœ‰็›ธไบค๏ผŒๆฒ’ๆœ‰ๅฐฑ็›ดๆŽฅ่ทณๆŽ‰๏ผŒไปฅ็ฏ€็œๆ•ˆ็Ž‡ + if !n.Bounds.Intersects(rangeRect) { + return result + } + + // ๅฆ‚ๆžœๆœๅฐ‹็ฏ„ๅœ่ทŸ็•ถๅ‰้ ˜ๅŸŸ็›ธไบค๏ผŒๆชขๆŸฅ่ฉฒ้ ˜ๅŸŸๆœ‰ๅคšๅฐ‘็‰ฉ้ซ”ๅŒ…ๅซๅœจๆœๅฐ‹็ฏ„ๅœไธญ๏ผŒไธฆๅขžๅŠ ่‡ณ result ไธญ + for _, point := range n.Points { + if rangeRect.Contains(point) && !context.Visited[point] { + result = append(result, point) + context.Visited[point] = true + } + } + + if n.NW == nil { + return result + } + + result = append(result, n.NW.queryRange(rangeRect, context)...) + result = append(result, n.NE.queryRange(rangeRect, context)...) + result = append(result, n.SW.queryRange(rangeRect, context)...) + result = append(result, n.SE.queryRange(rangeRect, context)...) + + return result +} diff --git a/structures/Quadtree/Quadtree_test.go b/structures/Quadtree/Quadtree_test.go new file mode 100644 index 000000000..ad6bbbf17 --- /dev/null +++ b/structures/Quadtree/Quadtree_test.go @@ -0,0 +1,79 @@ +package quadtree + +import ( + "fmt" + "testing" +) + +func TestQuadtree(t *testing.T) { + // ๅปบ็ซ‹ไธ€ๅ€‹root node๏ผŒ่กจ็คบๆ•ดๆ•ดๅ€‹็ฉบ้–“ + rootNode := NewQuadTreeNode(Rect{0, 0, 100, 100}) + + // ๆ’ๅ…ฅไธ€ไบ›้ปž + points := []Point{ + {20, 20}, + {30, 30}, + {40, 40}, + {50, 50}, + {60, 60}, + } + + for _, point := range points { + rootNode.Insert(point) + } + + // ๆŸฅ่ฉขไธ€ๅ€‹็ฏ„ๅœๅ…ง็š„้ปž + queryRect := Rect{25, 25, 55, 55} + result := rootNode.QueryRange(queryRect) + + fmt.Println("Points within the query range:") + for _, point := range result { + fmt.Printf("X: %.2f, Y: %.2f\n", point.X, point.Y) + } +} + +func TestQuadtree2(t *testing.T) { + // ๅ‰ตๅปบไธ€ๅ€‹็ฐกๅ–ฎ็š„ๅ››ๅ‰ๆจน + rootBounds := NewRect(0, 0, 10, 10) + quadtree := NewQuadTreeNode(rootBounds) + + // ๆ’ๅ…ฅไธ€ไบ›้ปž + points := []Point{ + {1, 1}, + {2, 2}, + {7, 7}, + {8, 8}, + {5, 5}, + } + + for _, point := range points { + quadtree.Insert(point) + } + + // ๆธฌ่ฉฆ้ปžๆ˜ฏๅฆๅญ˜ๅœจ + for _, point := range points { + if !quadtree.Bounds.Contains(point) { + t.Errorf("Point should be inside the bounds") + } + } + + // ๆธฌ่ฉฆ้ปžๆ˜ฏๅฆๅฏไปฅๆŸฅ่ฉขๅˆฐ + queryRect := NewRect(1, 1, 6, 6) + queryResult := quadtree.QueryRange(queryRect) + fmt.Println(queryResult) + + if len(queryResult) != 3 { + t.Errorf("Query should return 3 points") + } + + // ๆธฌ่ฉฆๅˆช้™ค้ปž + pointToDelete := Point{2, 2} + quadtree.Delete(pointToDelete) + + // ๅ†ๆฌกๆŸฅ่ฉข + queryResult = quadtree.QueryRange(queryRect) + + if len(queryResult) != 2 { + t.Errorf("Query should return 2 points after deletion") + } +} diff --git a/structures/Queue.go b/structures/Queue.go new file mode 100644 index 000000000..69431c666 --- /dev/null +++ b/structures/Queue.go @@ -0,0 +1,33 @@ +package structures + +// Queue ๆ˜ฏ็”จไบŽๅญ˜ๆ”พ int ็š„้˜Ÿๅˆ— +type Queue struct { + nums []int +} + +// NewQueue ่ฟ”ๅ›ž *kit.Queue +func NewQueue() *Queue { + return &Queue{nums: []int{}} +} + +// Push ๆŠŠ n ๆ”พๅ…ฅ้˜Ÿๅˆ— +func (q *Queue) Push(n int) { + q.nums = append(q.nums, n) +} + +// Pop ไปŽ q ไธญๅ–ๅ‡บๆœ€ๅ…ˆ่ฟ›ๅ…ฅ้˜Ÿๅˆ—็š„ๅ€ผ +func (q *Queue) Pop() int { + res := q.nums[0] + q.nums = q.nums[1:] + return res +} + +// Len ่ฟ”ๅ›ž q ็š„้•ฟๅบฆ +func (q *Queue) Len() int { + return len(q.nums) +} + +// IsEmpty ๅ้ฆˆ q ๆ˜ฏๅฆไธบ็ฉบ +func (q *Queue) IsEmpty() bool { + return q.Len() == 0 +} diff --git a/structures/Queue_test.go b/structures/Queue_test.go new file mode 100644 index 000000000..9b10a39b3 --- /dev/null +++ b/structures/Queue_test.go @@ -0,0 +1,27 @@ +package structures + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_Queue(t *testing.T) { + ast := assert.New(t) + + q := NewQueue() + ast.True(q.IsEmpty(), "ๆฃ€ๆŸฅๆ–ฐๅปบ็š„ q ๆ˜ฏๅฆไธบ็ฉบ") + + start, end := 0, 100 + + for i := start; i < end; i++ { + q.Push(i) + ast.Equal(i-start+1, q.Len(), "Push ๅŽๆฃ€ๆŸฅ q ็š„้•ฟๅบฆใ€‚") + } + + for i := start; i < end; i++ { + ast.Equal(i, q.Pop(), "ไปŽ q ไธญ pop ๅ‡บๆ•ฐๆฅใ€‚") + } + + ast.True(q.IsEmpty(), "ๆฃ€ๆŸฅ Pop ๅฎŒๆฏ•ๅŽ็š„ q ๆ˜ฏๅฆไธบ็ฉบ") +} diff --git a/structures/Stack.go b/structures/Stack.go new file mode 100644 index 000000000..452c24854 --- /dev/null +++ b/structures/Stack.go @@ -0,0 +1,33 @@ +package structures + +// Stack ๆ˜ฏ็”จไบŽๅญ˜ๆ”พ int ็š„ ๆ ˆ +type Stack struct { + nums []int +} + +// NewStack ่ฟ”ๅ›ž *kit.Stack +func NewStack() *Stack { + return &Stack{nums: []int{}} +} + +// Push ๆŠŠ n ๆ”พๅ…ฅ ๆ ˆ +func (s *Stack) Push(n int) { + s.nums = append(s.nums, n) +} + +// Pop ไปŽ s ไธญๅ–ๅ‡บๆœ€ๅŽๆ”พๅ…ฅ ๆ ˆ ็š„ๅ€ผ +func (s *Stack) Pop() int { + res := s.nums[len(s.nums)-1] + s.nums = s.nums[:len(s.nums)-1] + return res +} + +// Len ่ฟ”ๅ›ž s ็š„้•ฟๅบฆ +func (s *Stack) Len() int { + return len(s.nums) +} + +// IsEmpty ๅ้ฆˆ s ๆ˜ฏๅฆไธบ็ฉบ +func (s *Stack) IsEmpty() bool { + return s.Len() == 0 +} diff --git a/structures/Stack_test.go b/structures/Stack_test.go new file mode 100644 index 000000000..b0c6c60a0 --- /dev/null +++ b/structures/Stack_test.go @@ -0,0 +1,27 @@ +package structures + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_Stack(t *testing.T) { + ast := assert.New(t) + + s := NewStack() + ast.True(s.IsEmpty(), "ๆฃ€ๆŸฅๆ–ฐๅปบ็š„ s ๆ˜ฏๅฆไธบ็ฉบ") + + start, end := 0, 100 + + for i := start; i < end; i++ { + s.Push(i) + ast.Equal(i-start+1, s.Len(), "Push ๅŽๆฃ€ๆŸฅ q ็š„้•ฟๅบฆใ€‚") + } + + for i := end - 1; i >= start; i-- { + ast.Equal(i, s.Pop(), "ไปŽ s ไธญ pop ๅ‡บๆ•ฐๆฅใ€‚") + } + + ast.True(s.IsEmpty(), "ๆฃ€ๆŸฅ Pop ๅฎŒๆฏ•ๅŽ็š„ s ๆ˜ฏๅฆไธบ็ฉบ") +} diff --git a/structures/TreeNode.go b/structures/TreeNode.go new file mode 100644 index 000000000..f6edb9c4b --- /dev/null +++ b/structures/TreeNode.go @@ -0,0 +1,233 @@ +package structures + +import ( + "fmt" +) + +// TreeNode is tree's node +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +// NULL ๆ–นไพฟๆทปๅŠ ๆต‹่ฏ•ๆ•ฐๆฎ +var NULL = -1 << 63 + +// Ints2TreeNode ๅˆฉ็”จ []int ็”Ÿๆˆ *TreeNode +func Ints2TreeNode(ints []int) *TreeNode { + n := len(ints) + if n == 0 { + return nil + } + + root := &TreeNode{ + Val: ints[0], + } + + queue := make([]*TreeNode, 1, n*2) + queue[0] = root + + i := 1 + for i < n { + node := queue[0] + queue = queue[1:] + + if i < n && ints[i] != NULL { + node.Left = &TreeNode{Val: ints[i]} + queue = append(queue, node.Left) + } + i++ + + if i < n && ints[i] != NULL { + node.Right = &TreeNode{Val: ints[i]} + queue = append(queue, node.Right) + } + i++ + } + + return root +} + +// GetTargetNode ่ฟ”ๅ›ž Val = target ็š„ TreeNode +// root ไธญไธ€ๅฎšๆœ‰ node.Val = target +func GetTargetNode(root *TreeNode, target int) *TreeNode { + if root == nil || root.Val == target { + return root + } + + res := GetTargetNode(root.Left, target) + if res != nil { + return res + } + return GetTargetNode(root.Right, target) +} + +func indexOf(val int, nums []int) int { + for i, v := range nums { + if v == val { + return i + } + } + + msg := fmt.Sprintf("%d ไธๅญ˜ๅœจไบŽ %v ไธญ", val, nums) + panic(msg) +} + +// PreIn2Tree ๆŠŠ preorder ๅ’Œ inorder ๅˆ‡็‰‡่ฝฌๆขๆˆ ไบŒๅ‰ๆ ‘ +func PreIn2Tree(pre, in []int) *TreeNode { + if len(pre) != len(in) { + panic("preIn2Tree ไธญไธคไธชๅˆ‡็‰‡็š„้•ฟๅบฆไธ็›ธ็ญ‰") + } + + if len(in) == 0 { + return nil + } + + res := &TreeNode{ + Val: pre[0], + } + + if len(in) == 1 { + return res + } + + idx := indexOf(res.Val, in) + + res.Left = PreIn2Tree(pre[1:idx+1], in[:idx]) + res.Right = PreIn2Tree(pre[idx+1:], in[idx+1:]) + + return res +} + +// InPost2Tree ๆŠŠ inorder ๅ’Œ postorder ๅˆ‡็‰‡่ฝฌๆขๆˆ ไบŒๅ‰ๆ ‘ +func InPost2Tree(in, post []int) *TreeNode { + if len(post) != len(in) { + panic("inPost2Tree ไธญไธคไธชๅˆ‡็‰‡็š„้•ฟๅบฆไธ็›ธ็ญ‰") + } + + if len(in) == 0 { + return nil + } + + res := &TreeNode{ + Val: post[len(post)-1], + } + + if len(in) == 1 { + return res + } + + idx := indexOf(res.Val, in) + + res.Left = InPost2Tree(in[:idx], post[:idx]) + res.Right = InPost2Tree(in[idx+1:], post[idx:len(post)-1]) + + return res +} + +// Tree2Preorder ๆŠŠ ไบŒๅ‰ๆ ‘ ่ฝฌๆขๆˆ preorder ็š„ๅˆ‡็‰‡ +func Tree2Preorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := []int{root.Val} + res = append(res, Tree2Preorder(root.Left)...) + res = append(res, Tree2Preorder(root.Right)...) + + return res +} + +// Tree2Inorder ๆŠŠ ไบŒๅ‰ๆ ‘่ฝฌๆขๆˆ inorder ็š„ๅˆ‡็‰‡ +func Tree2Inorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := Tree2Inorder(root.Left) + res = append(res, root.Val) + res = append(res, Tree2Inorder(root.Right)...) + + return res +} + +// Tree2Postorder ๆŠŠ ไบŒๅ‰ๆ ‘ ่ฝฌๆขๆˆ postorder ็š„ๅˆ‡็‰‡ +func Tree2Postorder(root *TreeNode) []int { + if root == nil { + return nil + } + + if root.Left == nil && root.Right == nil { + return []int{root.Val} + } + + res := Tree2Postorder(root.Left) + res = append(res, Tree2Postorder(root.Right)...) + res = append(res, root.Val) + + return res +} + +// Equal return ture if tn == a +func (tn *TreeNode) Equal(a *TreeNode) bool { + if tn == nil && a == nil { + return true + } + + if tn == nil || a == nil || tn.Val != a.Val { + return false + } + + return tn.Left.Equal(a.Left) && tn.Right.Equal(a.Right) +} + +// Tree2ints ๆŠŠ *TreeNode ๆŒ‰็…ง่กŒ่ฟ˜ๅŽŸๆˆ []int +func Tree2ints(tn *TreeNode) []int { + res := make([]int, 0, 1024) + + queue := []*TreeNode{tn} + + for len(queue) > 0 { + size := len(queue) + for i := 0; i < size; i++ { + nd := queue[i] + if nd == nil { + res = append(res, NULL) + } else { + res = append(res, nd.Val) + queue = append(queue, nd.Left, nd.Right) + } + } + queue = queue[size:] + } + + i := len(res) + for i > 0 && res[i-1] == NULL { + i-- + } + + return res[:i] +} + +// T2s convert *TreeNode to []int +func T2s(head *TreeNode, array *[]int) { + fmt.Printf("่ฟ่กŒๅˆฐ่ฟ™้‡Œไบ† head = %v array = %v\n", head, array) + // fmt.Printf("****array = %v\n", array) + // fmt.Printf("****head = %v\n", head.Val) + *array = append(*array, head.Val) + if head.Left != nil { + T2s(head.Left, array) + } + if head.Right != nil { + T2s(head.Right, array) + } +} diff --git a/structures/TreeNode_test.go b/structures/TreeNode_test.go new file mode 100644 index 000000000..dc75bf049 --- /dev/null +++ b/structures/TreeNode_test.go @@ -0,0 +1,166 @@ +package structures + +import ( + "reflect" + "testing" + + "github.com/stretchr/testify/assert" +) + +var ( + // ๅŒไธ€ไธช TreeNode ็š„ไธๅŒ่กจ่พพๆ–นๅผ + // 1 + // / \ + // 2 3 + // / \ / \ + // 4 5 6 7 + LeetCodeOrder = []int{1, 2, 3, 4, 5, 6, 7} + preOrder = []int{1, 2, 4, 5, 3, 6, 7} + inOrder = []int{4, 2, 5, 1, 6, 3, 7} + postOrder = []int{4, 5, 2, 6, 7, 3, 1} +) + +func Test_Ints2TreeNode(t *testing.T) { + ast := assert.New(t) + + expected := PreIn2Tree(preOrder, inOrder) + actual := Ints2TreeNode(LeetCodeOrder) + ast.Equal(expected, actual) + + actual = Ints2TreeNode([]int{}) + ast.Nil(actual) +} + +func Test_preIn2Tree(t *testing.T) { + ast := assert.New(t) + + actual := Tree2Postorder(PreIn2Tree(preOrder, inOrder)) + expected := postOrder + ast.Equal(expected, actual) + + ast.Panics(func() { PreIn2Tree([]int{1}, []int{}) }) + + ast.Nil(PreIn2Tree([]int{}, []int{})) +} + +func Test_inPost2Tree(t *testing.T) { + ast := assert.New(t) + + actual := Tree2Preorder(InPost2Tree(inOrder, postOrder)) + expected := preOrder + ast.Equal(expected, actual) + + ast.Panics(func() { InPost2Tree([]int{1}, []int{}) }) + + ast.Nil(InPost2Tree([]int{}, []int{})) +} + +func Test_tree2Ints(t *testing.T) { + ast := assert.New(t) + root := PreIn2Tree(preOrder, inOrder) + + ast.Equal(preOrder, Tree2Preorder(root)) + ast.Nil(Tree2Preorder(nil)) + + ast.Equal(inOrder, Tree2Inorder(root)) + ast.Nil(Tree2Inorder(nil)) + + ast.Equal(postOrder, Tree2Postorder(root)) + ast.Nil(Tree2Postorder(nil)) +} + +func Test_indexOf(t *testing.T) { + ast := assert.New(t) + + ast.Equal(1, indexOf(1, []int{0, 1, 2, 3})) + + ast.Panics(func() { indexOf(0, []int{1, 2, 3}) }) +} + +func Test_TreeNode_Equal(t *testing.T) { + type args struct { + a *TreeNode + } + tests := []struct { + name string + fields args + args args + want bool + }{ + + { + "็›ธ็ญ‰", + args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, + args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, + true, + }, + + { + "ไธ็›ธ็ญ‰", + args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, + args{Ints2TreeNode([]int{1, 2, 3, NULL, 5})}, + false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tn := tt.fields.a + if got := tn.Equal(tt.args.a); got != tt.want { + t.Errorf("TreeNode.Equal() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_GetTargetNode(t *testing.T) { + ints := []int{3, 5, 1, 6, 2, 0, 8, NULL, NULL, 7, 4} + root := Ints2TreeNode(ints) + + type args struct { + root *TreeNode + target int + } + tests := []struct { + name string + args args + want *TreeNode + }{ + + { + "ๆ‰พๅˆฐ root.Right.Right", + args{ + root: root, + target: 8, + }, + root.Right.Right, + }, + + { + "ๆ‰พๅˆฐ root.Left.Left", + args{ + root: root, + target: 6, + }, + root.Left.Left, + }, + + // + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := GetTargetNode(tt.args.root, tt.args.target); !reflect.DeepEqual(got, tt.want) { + t.Errorf("GetTargetNode() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_Tree2ints(t *testing.T) { + ast := assert.New(t) + + root := PreIn2Tree(preOrder, inOrder) + actual := LeetCodeOrder + expected := Tree2ints(root) + ast.Equal(expected, actual) +} diff --git a/structures/heap/FullBT_CompleteBT.jpg b/structures/heap/FullBT_CompleteBT.jpg new file mode 100644 index 000000000..b045cb343 Binary files /dev/null and b/structures/heap/FullBT_CompleteBT.jpg differ diff --git a/structures/heap/index.en.html b/structures/heap/index.en.html new file mode 100644 index 000000000..b4d11234f --- /dev/null +++ b/structures/heap/index.en.html @@ -0,0 +1,3956 @@ + + + + + + + Golang Container Heap ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                + + + + + + + + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                + +

                                                                                                                                                                                                                                                Golang : container/heap

                                                                                                                                                                                                                                                Heap是什麼

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                Wiki: https://zh.wikipedia.org/wiki/%E5%A0%86%E7%A9%8D

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                堆積(Heap)是電腦科學中的一種特別的完全二元樹。 +若是滿足以下特性,即可稱為堆積:「給定堆積中任意節點P和C,若P是C的母節點,那麼P的值會小於等於(或大於等於)C的值」。 +若母節點的值恆小於等於子節點的值,此堆積稱為最小堆積(min heap); +反之,若母節點的值恆大於等於子節點的值,此堆積稱為最大堆積(max heap)。 +在堆積中最頂端的那一個節點,稱作根節點(root node),根節點本身沒有母節點(parent node)。

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                container/heap 提供的方法

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                heap包為實現了 heap.Interface 的類型提供了堆方法:Init/Push/Pop/Remove/Fix。 container/heap 為最小堆, +即每個節點的值都小於它的子樹的所有元素的值(A heap is a tree with the property that each node is the minimum-valued node in its subtree)。

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                heap:

                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                package heap
                                                                                                                                                                                                                                                +// ...
                                                                                                                                                                                                                                                +// Note that Push and Pop in this interface are for package heap's
                                                                                                                                                                                                                                                +// implementation to call. To add and remove things from the heap,
                                                                                                                                                                                                                                                +// use heap.Push and heap.Pop.
                                                                                                                                                                                                                                                +type Interface interface {
                                                                                                                                                                                                                                                +    sort.Interface
                                                                                                                                                                                                                                                +    Push(x any) // add x as element Len()
                                                                                                                                                                                                                                                +    Pop() any   // remove and return element Len() - 1.
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                sort:

                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                package sort
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +// An implementation of Interface can be sorted by the routines in this package.
                                                                                                                                                                                                                                                +// The methods refer to elements of the underlying collection by integer index.
                                                                                                                                                                                                                                                +type Interface interface {
                                                                                                                                                                                                                                                +    // Len is the number of elements in the collection.
                                                                                                                                                                                                                                                +    Len() int
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +    // Less reports whether the element with index i
                                                                                                                                                                                                                                                +    // must sort before the element with index j.
                                                                                                                                                                                                                                                +    //
                                                                                                                                                                                                                                                +    // If both Less(i, j) and Less(j, i) are false,
                                                                                                                                                                                                                                                +    // then the elements at index i and j are considered equal.
                                                                                                                                                                                                                                                +    // Sort may place equal elements in any order in the final result,
                                                                                                                                                                                                                                                +    // while Stable preserves the original input order of equal elements.
                                                                                                                                                                                                                                                +    //
                                                                                                                                                                                                                                                +    // Less must describe a transitive ordering:
                                                                                                                                                                                                                                                +    //  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
                                                                                                                                                                                                                                                +    //  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
                                                                                                                                                                                                                                                +    //
                                                                                                                                                                                                                                                +    // Note that floating-point comparison (the < operator on float32 or float64 values)
                                                                                                                                                                                                                                                +    // is not a transitive ordering when not-a-number (NaN) values are involved.
                                                                                                                                                                                                                                                +    // See Float64Slice.Less for a correct implementation for floating-point values.
                                                                                                                                                                                                                                                +    Less(i, j int) bool
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +    // Swap swaps the elements with indexes i and j.
                                                                                                                                                                                                                                                +    Swap(i, j int)
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                由於 heap.Interface 包含了 sort.Interface ,所以,目標類型需要包含如下方法:Len/Less/Swap ,Push/Pop。

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                container/heap 可用在哪

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                container/heap包可以用來構造優先順序佇列。

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                https://go.dev/play/p/77zrF3PurO4

                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                // This example demonstrates a priority queue built using the heap interface.
                                                                                                                                                                                                                                                +package main
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +import (
                                                                                                                                                                                                                                                +    "container/heap"
                                                                                                                                                                                                                                                +    "fmt"
                                                                                                                                                                                                                                                +)
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +// An Item is something we manage in a priority queue.
                                                                                                                                                                                                                                                +type Item struct {
                                                                                                                                                                                                                                                +    value    string // The value of the item; arbitrary.
                                                                                                                                                                                                                                                +    priority int    // The priority of the item in the queue.
                                                                                                                                                                                                                                                +    // The index is needed by update and is maintained by the heap.Interface methods.
                                                                                                                                                                                                                                                +    index int // The index of the item in the heap.
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +// A PriorityQueue implements heap.Interface and holds Items.
                                                                                                                                                                                                                                                +type PriorityQueue []*Item
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +func (pq PriorityQueue) Len() int { return len(pq) }
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +func (pq PriorityQueue) Less(i, j int) bool {
                                                                                                                                                                                                                                                +    // We want Pop to give us the highest, not lowest, priority so we use greater than here.
                                                                                                                                                                                                                                                +    return pq[i].priority > pq[j].priority
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +func (pq PriorityQueue) Swap(i, j int) {
                                                                                                                                                                                                                                                +    pq[i], pq[j] = pq[j], pq[i]
                                                                                                                                                                                                                                                +    pq[i].index = i
                                                                                                                                                                                                                                                +    pq[j].index = j
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +func (pq *PriorityQueue) Push(x interface{}) {
                                                                                                                                                                                                                                                +    n := len(*pq)
                                                                                                                                                                                                                                                +    item := x.(*Item)
                                                                                                                                                                                                                                                +    item.index = n
                                                                                                                                                                                                                                                +    *pq = append(*pq, item)
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +func (pq *PriorityQueue) Pop() interface{} {
                                                                                                                                                                                                                                                +    old := *pq
                                                                                                                                                                                                                                                +    n := len(old)
                                                                                                                                                                                                                                                +    item := old[n-1]
                                                                                                                                                                                                                                                +    item.index = -1 // for safety
                                                                                                                                                                                                                                                +    *pq = old[0 : n-1]
                                                                                                                                                                                                                                                +    return item
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +// update modifies the priority and value of an Item in the queue.
                                                                                                                                                                                                                                                +func (pq *PriorityQueue) update(item *Item, value string, priority int) {
                                                                                                                                                                                                                                                +    item.value = value
                                                                                                                                                                                                                                                +    item.priority = priority
                                                                                                                                                                                                                                                +    heap.Fix(pq, item.index)
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                PriorityQueue 本質上是個 *Item 陣列,其Len/Less/Swap是比較常見的陣列用來sort需要定義的函數,而Push、Pop則是使用數位來插入、的方法。 PriorityQueue 還提供了update方法。 注意由於通常希望優先順序佇列Pop出來的是優先順序最高的元素,所以Less方法是反著寫的。

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                定義了以上方法以後, PriorityQueue 就具備了使用 container/heap 包的條件。

                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                如下代碼,先從items map出發定義了一個pq陣列,長度為hash的size,並調用 heap.Init 初始化pq; +之後向佇列中增加了一個優先順序為1的元素,並更新該元素的佇列; 最後從佇列中依此Pop,可見元素在Pop時是依照優先順序排序的。

                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                // This example creates a PriorityQueue with some items, adds and manipulates an item,
                                                                                                                                                                                                                                                +// and then removes the items in priority order.
                                                                                                                                                                                                                                                +func main() {
                                                                                                                                                                                                                                                +    // Some items and their priorities.
                                                                                                                                                                                                                                                +    items := map[string]int{
                                                                                                                                                                                                                                                +        "banana": 3, "apple": 2, "pear": 4,
                                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +    // Create a priority queue, put the items in it, and
                                                                                                                                                                                                                                                +    // establish the priority queue (heap) invariants.
                                                                                                                                                                                                                                                +    pq := make(PriorityQueue, len(items))
                                                                                                                                                                                                                                                +    i := 0
                                                                                                                                                                                                                                                +    for value, priority := range items {
                                                                                                                                                                                                                                                +        pq[i] = &Item{
                                                                                                                                                                                                                                                +            value:    value,
                                                                                                                                                                                                                                                +            priority: priority,
                                                                                                                                                                                                                                                +            index:    i,
                                                                                                                                                                                                                                                +        }
                                                                                                                                                                                                                                                +        i++
                                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                                +    heap.Init(&pq)
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +    // Insert a new item and then modify its priority.
                                                                                                                                                                                                                                                +    item := &Item{
                                                                                                                                                                                                                                                +        value:    "orange",
                                                                                                                                                                                                                                                +        priority: 1,
                                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                                +    heap.Push(&pq, item)
                                                                                                                                                                                                                                                +    pq.update(item, item.value, 5)
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +    // Take the items out; they arrive in decreasing priority order.
                                                                                                                                                                                                                                                +    for pq.Len() > 0 {
                                                                                                                                                                                                                                                +        item := heap.Pop(&pq).(*Item)
                                                                                                                                                                                                                                                +        fmt.Printf("%.2d:%s index:%d \n", item.priority, item.value, item.index)
                                                                                                                                                                                                                                                +    }
                                                                                                                                                                                                                                                +}
                                                                                                                                                                                                                                                +// Output:
                                                                                                                                                                                                                                                +// 05:orange index:-1 
                                                                                                                                                                                                                                                +// 04:pear index:-1 
                                                                                                                                                                                                                                                +// 03:banana index:-1 
                                                                                                                                                                                                                                                +// 02:apple index:-1
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +

                                                                                                                                                                                                                                                Reference

                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                + +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                + +

                                                                                                                                                                                                                                                results matching ""

                                                                                                                                                                                                                                                +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                                                  No results matching ""

                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  + + + + + + + + + + +
                                                                                                                                                                                                                                                  + + +
                                                                                                                                                                                                                                                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/structures/index.html b/structures/index.html new file mode 100644 index 000000000..5354d9eb3 --- /dev/null +++ b/structures/index.html @@ -0,0 +1,3799 @@ + + + + + + + Structures ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  + + + + + + + + +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                                                  來源

                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                                  + + +
                                                                                                                                                                                                                                                  + +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                  + +

                                                                                                                                                                                                                                                  results matching ""

                                                                                                                                                                                                                                                  +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    No results matching ""

                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    + + + + + + + + + + +
                                                                                                                                                                                                                                                    + + +
                                                                                                                                                                                                                                                    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tags.html b/tags.html new file mode 100644 index 000000000..4e0bd8aa6 --- /dev/null +++ b/tags.html @@ -0,0 +1,4493 @@ + + + + + + + Tags ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    + + + + + + + + +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Tags

                                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                                    © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39

                                                                                                                                                                                                                                                    +

                                                                                                                                                                                                                                                    Algorithm

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Golang

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    A1B2C3

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Interview

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Algorithms

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Go

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Easy

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Find Target Last Index

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Right Bound

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Left Bound

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Intersection

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Search Graph

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    BFS

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    WeightedEditDistance

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Dynamic Programming

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    CodeSignal

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Bank Requests

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Codility

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Iterations

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Painless

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Bitwise Manipulation

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Array

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Multiple Pointers

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    LeetCode

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Easy/Medium/Hard

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    LEETCODETITLE

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Medium

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Add Two Numbers

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Linked List

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Math

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Recursion

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Amazon

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Apple

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Facebook

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Microsoft

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Bloomberg

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Longest Substring Without Repeating Characters

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Sliding Window

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    DP

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Google

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Adobe

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    3Sum

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Two Pointers

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Sorting

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Valid Parentheses

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Merge Two Sorted Lists

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Find the Index of the First Occurrence in a String

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    String

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    String Matching

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Backtracking

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Group Anagrams

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Blind75

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Climbing Stairs

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Hard

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Edit Distance

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Sort

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Subsets

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Stack

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Same Tree

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Tree

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Construct Binary Tree from Preorder and Inorder Traversal

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Hash Table

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Divide and Conquer

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Binary Tree

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Balanced Binary Tree

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    DFS

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Slide Windows

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Best Time to Buy and Sell Stock

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    array

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Valid Palindrome

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Longest Consecutive Sequence

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Union Find

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Spotify

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Copy List with Random Pointer

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    /Medium

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    143. Reorder List

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Two Sum II Input Array Is Sorted

                                                                                                                                                                                                                                                    + + + +

                                                                                                                                                                                                                                                    Reverse Linked List

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Kth Largest Element in an Array

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Heap

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Priority Queue

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Contains Duplicate

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Invert Binary Tree

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Product of Array Except Self

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Prefix Sum

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Valid Anagram

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Move Zeroes

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Patience Sorting

                                                                                                                                                                                                                                                    + + + +

                                                                                                                                                                                                                                                    Coin Change

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Top K Frequent Elements

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    heap

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Insert Delete GetRandom O(1)

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Hash

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Insert Delete GetRandom O(1) Duplicates allowed

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Fizz Buzz

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    string

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    math

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Diameter of Binary Tree

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Bit Manipulation

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Max Area of Island

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Array & String

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Matrix

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Kth Largest Element in a Stream

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Flood Fill

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Min Cost Climbing Stairs

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Last Stone Weight

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Fizz Buzz Multithreaded

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    Concurrency

                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    container/heap

                                                                                                                                                                                                                                                    + + + +
                                                                                                                                                                                                                                                    + +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                    + +

                                                                                                                                                                                                                                                    results matching ""

                                                                                                                                                                                                                                                    +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                                                      No results matching ""

                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      + + + + + + + + + + +
                                                                                                                                                                                                                                                      + + +
                                                                                                                                                                                                                                                      + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/template/CLRUCache.go b/template/CLRUCache.go new file mode 100644 index 000000000..03b5115c6 --- /dev/null +++ b/template/CLRUCache.go @@ -0,0 +1,176 @@ +package template + +import ( + "container/list" + "hash/fnv" + "sync" +) + +type command int + +const ( + // MoveToFront define + MoveToFront command = iota + // PushFront define + PushFront + // Delete define + Delete +) + +type clear struct { + done chan struct{} +} + +// CLRUCache define: High Concurrency LRUCache +type CLRUCache struct { + sync.RWMutex + cap int + list *list.List + buckets []*bucket + bucketMask uint32 + deletePairs chan *list.Element + movePairs chan *list.Element + control chan interface{} +} + +// Pair define +type Pair struct { + key string + value interface{} + cmd command +} + +// New define +func New(capacity int) *CLRUCache { + c := &CLRUCache{ + cap: capacity, + list: list.New(), + bucketMask: uint32(1024) - 1, + buckets: make([]*bucket, 1024), + } + for i := 0; i < 1024; i++ { + c.buckets[i] = &bucket{ + keys: make(map[string]*list.Element), + } + } + c.restart() + return c +} + +// Get define +func (c *CLRUCache) Get(key string) interface{} { + el := c.bucket(key).get(key) + if el == nil { + return nil + } + c.move(el) + return el.Value.(Pair).value +} + +// Put define +func (c *CLRUCache) Put(key string, value interface{}) { + el, exist := c.bucket(key).set(key, value) + if exist != nil { + c.deletePairs <- exist + } + c.move(el) +} + +func (c *CLRUCache) move(el *list.Element) { + select { + case c.movePairs <- el: + default: + } +} + +// Delete define +func (c *CLRUCache) Delete(key string) bool { + el := c.bucket(key).delete(key) + if el != nil { + c.deletePairs <- el + return true + } + return false +} + +// Clear define +func (c *CLRUCache) Clear() { + done := make(chan struct{}) + c.control <- clear{done: done} + <-done +} + +// Count define +func (c *CLRUCache) Count() int { + count := 0 + for _, b := range c.buckets { + count += b.pairCount() + } + return count +} + +func (c *CLRUCache) bucket(key string) *bucket { + h := fnv.New32a() + h.Write([]byte(key)) + return c.buckets[h.Sum32()&c.bucketMask] +} + +func (c *CLRUCache) stop() { + close(c.movePairs) + <-c.control +} + +func (c *CLRUCache) restart() { + c.deletePairs = make(chan *list.Element, 128) + c.movePairs = make(chan *list.Element, 128) + c.control = make(chan interface{}) + go c.worker() +} + +func (c *CLRUCache) worker() { + defer close(c.control) + for { + select { + case el, ok := <-c.movePairs: + if ok == false { + goto clean + } + if c.doMove(el) && c.list.Len() > c.cap { + el := c.list.Back() + c.list.Remove(el) + c.bucket(el.Value.(Pair).key).delete(el.Value.(Pair).key) + } + case el := <-c.deletePairs: + c.list.Remove(el) + case control := <-c.control: + switch msg := control.(type) { + case clear: + for _, bucket := range c.buckets { + bucket.clear() + } + c.list = list.New() + msg.done <- struct{}{} + } + } + } +clean: + for { + select { + case el := <-c.deletePairs: + c.list.Remove(el) + default: + close(c.deletePairs) + return + } + } +} + +func (c *CLRUCache) doMove(el *list.Element) bool { + if el.Value.(Pair).cmd == MoveToFront { + c.list.MoveToFront(el) + return false + } + newel := c.list.PushFront(el.Value.(Pair)) + c.bucket(el.Value.(Pair).key).update(el.Value.(Pair).key, newel) + return true +} diff --git a/template/CLRUCache_test.go b/template/CLRUCache_test.go new file mode 100644 index 000000000..fa1722c54 --- /dev/null +++ b/template/CLRUCache_test.go @@ -0,0 +1,130 @@ +package template + +import ( + "container/list" + "math/rand" + "strconv" + "sync" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func Test_CLRUCache(t *testing.T) { + obj := New(2) + time.Sleep(150 * time.Millisecond) + obj.Put("1", 1) + time.Sleep(150 * time.Millisecond) + obj.Put("2", 2) + time.Sleep(150 * time.Millisecond) + param1 := obj.Get("1") + time.Sleep(150 * time.Millisecond) + assert.Equal(t, 1, param1) + obj.Put("3", 3) + time.Sleep(150 * time.Millisecond) + param1 = obj.Get("2") + assert.Equal(t, nil, param1) + obj.Put("4", 4) + time.Sleep(150 * time.Millisecond) + param1 = obj.Get("1") + time.Sleep(150 * time.Millisecond) + assert.Equal(t, nil, param1) + param1 = obj.Get("3") + time.Sleep(150 * time.Millisecond) + assert.Equal(t, 3, param1) + param1 = obj.Get("4") + time.Sleep(150 * time.Millisecond) + assert.Equal(t, 4, param1) +} + +func MList2Ints(lru *CLRUCache) [][]interface{} { + res := [][]interface{}{} + for head := lru.list.Front(); head != nil; head = head.Next() { + tmp := []interface{}{head.Value.(Pair).key, head.Value.(Pair).value} + res = append(res, tmp) + } + return res +} + +func BenchmarkGetAndPut1(b *testing.B) { + b.ResetTimer() + obj := New(128) + wg := sync.WaitGroup{} + wg.Add(b.N * 2) + for i := 0; i < b.N; i++ { + go func() { + defer wg.Done() + obj.Get(strconv.Itoa(rand.Intn(200))) + }() + go func() { + defer wg.Done() + obj.Put(strconv.Itoa(rand.Intn(200)), strconv.Itoa(rand.Intn(200))) + }() + } + wg.Wait() +} + +type Cache struct { + sync.RWMutex + Cap int + Keys map[string]*list.Element + List *list.List +} + +type pair struct { + K, V string +} + +func NewLRUCache(capacity int) Cache { + return Cache{ + Cap: capacity, + Keys: make(map[string]*list.Element), + List: list.New(), + } +} + +func (c *Cache) Get(key string) interface{} { + c.Lock() + if el, ok := c.Keys[key]; ok { + c.List.MoveToFront(el) + return el.Value.(pair).V + } + c.Unlock() + return nil +} + +func (c *Cache) Put(key string, value string) { + c.Lock() + if el, ok := c.Keys[key]; ok { + el.Value = pair{K: key, V: value} + c.List.MoveToFront(el) + } else { + el := c.List.PushFront(pair{K: key, V: value}) + c.Keys[key] = el + } + if c.List.Len() > c.Cap { + el := c.List.Back() + c.List.Remove(el) + delete(c.Keys, el.Value.(pair).K) + } + c.Unlock() +} + +func BenchmarkGetAndPut2(b *testing.B) { + b.ResetTimer() + obj := NewLRUCache(128) + wg := sync.WaitGroup{} + wg.Add(b.N * 2) + for i := 0; i < b.N; i++ { + go func() { + defer wg.Done() + obj.Get(strconv.Itoa(rand.Intn(200))) + }() + go func() { + defer wg.Done() + obj.Put(strconv.Itoa(rand.Intn(200)), strconv.Itoa(rand.Intn(200))) + }() + } + wg.Wait() +} diff --git a/template/LFUCache.go b/template/LFUCache.go new file mode 100644 index 000000000..74a8a9a9d --- /dev/null +++ b/template/LFUCache.go @@ -0,0 +1,196 @@ +package template + +import "container/list" + +// LFUCache define +type LFUCache struct { + nodes map[int]*list.Element + lists map[int]*list.List + capacity int + min int +} + +type node struct { + key int + value int + frequency int +} + +// Constructor define +func Constructor(capacity int) LFUCache { + return LFUCache{nodes: make(map[int]*list.Element), + lists: make(map[int]*list.List), + capacity: capacity, + min: 0, + } +} + +// Get define +func (lfuCache *LFUCache) Get(key int) int { + value, ok := lfuCache.nodes[key] + if !ok { + return -1 + } + currentNode := value.Value.(*node) + lfuCache.lists[currentNode.frequency].Remove(value) + currentNode.frequency++ + if _, ok := lfuCache.lists[currentNode.frequency]; !ok { + lfuCache.lists[currentNode.frequency] = list.New() + } + newList := lfuCache.lists[currentNode.frequency] + newNode := newList.PushFront(currentNode) + lfuCache.nodes[key] = newNode + if currentNode.frequency-1 == lfuCache.min && lfuCache.lists[currentNode.frequency-1].Len() == 0 { + lfuCache.min++ + } + return currentNode.value +} + +// Put define +func (lfuCache *LFUCache) Put(key int, value int) { + if lfuCache.capacity == 0 { + return + } + if currentValue, ok := lfuCache.nodes[key]; ok { + currentNode := currentValue.Value.(*node) + currentNode.value = value + lfuCache.Get(key) + return + } + if lfuCache.capacity == len(lfuCache.nodes) { + currentList := lfuCache.lists[lfuCache.min] + backNode := currentList.Back() + delete(lfuCache.nodes, backNode.Value.(*node).key) + currentList.Remove(backNode) + } + lfuCache.min = 1 + currentNode := &node{ + key: key, + value: value, + frequency: 1, + } + if _, ok := lfuCache.lists[1]; !ok { + lfuCache.lists[1] = list.New() + } + newList := lfuCache.lists[1] + newNode := newList.PushFront(currentNode) + lfuCache.nodes[key] = newNode +} + +/** + * Your LFUCache object will be instantiated and called as such: + * obj := Constructor(capacity); + * param_1 := obj.Get(key); + * obj.Put(key,value); + */ + +// Index Priority Queue +// import "container/heap" + +// type LFUCache struct { +// capacity int +// pq PriorityQueue +// hash map[int]*Item +// counter int +// } + +// func Constructor(capacity int) LFUCache { +// lfu := LFUCache{ +// pq: PriorityQueue{}, +// hash: make(map[int]*Item, capacity), +// capacity: capacity, +// } +// return lfu +// } + +// func (this *LFUCache) Get(key int) int { +// if this.capacity == 0 { +// return -1 +// } +// if item, ok := this.hash[key]; ok { +// this.counter++ +// this.pq.update(item, item.value, item.frequency+1, this.counter) +// return item.value +// } +// return -1 +// } + +// func (this *LFUCache) Put(key int, value int) { +// if this.capacity == 0 { +// return +// } +// // fmt.Printf("Put %d\n", key) +// this.counter++ +// // ๅฆ‚ๆžœๅญ˜ๅœจ๏ผŒๅขžๅŠ  frequency๏ผŒๅ†่ฐƒๆ•ดๅ † +// if item, ok := this.hash[key]; ok { +// this.pq.update(item, value, item.frequency+1, this.counter) +// return +// } +// // ๅฆ‚ๆžœไธๅญ˜ๅœจไธ”็ผ“ๅญ˜ๆปกไบ†๏ผŒ้œ€่ฆๅˆ ้™คใ€‚ๅœจ hashmap ๅ’Œ pq ไธญๅˆ ้™คใ€‚ +// if len(this.pq) == this.capacity { +// item := heap.Pop(&this.pq).(*Item) +// delete(this.hash, item.key) +// } +// // ๆ–ฐๅปบ็ป“็‚น๏ผŒๅœจ hashmap ๅ’Œ pq ไธญๆทปๅŠ ใ€‚ +// item := &Item{ +// value: value, +// key: key, +// count: this.counter, +// } +// heap.Push(&this.pq, item) +// this.hash[key] = item +// } + +// // An Item is something we manage in a priority queue. +// type Item struct { +// value int // The value of the item; arbitrary. +// key int +// frequency int // The priority of the item in the queue. +// count int // use for evicting the oldest element +// // The index is needed by update and is maintained by the heap.Interface methods. +// index int // The index of the item in the heap. +// } + +// // A PriorityQueue implements heap.Interface and holds Items. +// type PriorityQueue []*Item + +// func (pq PriorityQueue) Len() int { return len(pq) } + +// func (pq PriorityQueue) Less(i, j int) bool { +// // We want Pop to give us the highest, not lowest, priority so we use greater than here. +// if pq[i].frequency == pq[j].frequency { +// return pq[i].count < pq[j].count +// } +// return pq[i].frequency < pq[j].frequency +// } + +// func (pq PriorityQueue) Swap(i, j int) { +// pq[i], pq[j] = pq[j], pq[i] +// pq[i].index = i +// pq[j].index = j +// } + +// func (pq *PriorityQueue) Push(x interface{}) { +// n := len(*pq) +// item := x.(*Item) +// item.index = n +// *pq = append(*pq, item) +// } + +// func (pq *PriorityQueue) Pop() interface{} { +// old := *pq +// n := len(old) +// item := old[n-1] +// old[n-1] = nil // avoid memory leak +// item.index = -1 // for safety +// *pq = old[0 : n-1] +// return item +// } + +// // update modifies the priority and value of an Item in the queue. +// func (pq *PriorityQueue) update(item *Item, value int, frequency int, count int) { +// item.value = value +// item.count = count +// item.frequency = frequency +// heap.Fix(pq, item.index) +// } diff --git a/template/LRUCache.go b/template/LRUCache.go new file mode 100644 index 000000000..581f42a8c --- /dev/null +++ b/template/LRUCache.go @@ -0,0 +1,139 @@ +package template + +// LRUCache define +type LRUCache struct { + head, tail *Node + keys map[int]*Node + capacity int +} + +// Node define +type Node struct { + key, val int + prev, next *Node +} + +// ConstructorLRU define +func ConstructorLRU(capacity int) LRUCache { + return LRUCache{keys: make(map[int]*Node), capacity: capacity} +} + +// Get define +func (lruCache *LRUCache) Get(key int) int { + if node, ok := lruCache.keys[key]; ok { + lruCache.Remove(node) + lruCache.Add(node) + return node.val + } + return -1 +} + +// Put define +func (lruCache *LRUCache) Put(key int, value int) { + node, ok := lruCache.keys[key] + if ok { + node.val = value + lruCache.Remove(node) + lruCache.Add(node) + return + } + node = &Node{key: key, val: value} + lruCache.keys[key] = node + lruCache.Add(node) + if len(lruCache.keys) > lruCache.capacity { + delete(lruCache.keys, lruCache.tail.key) + lruCache.Remove(lruCache.tail) + } +} + +// Add define +func (lruCache *LRUCache) Add(node *Node) { + node.prev = nil + node.next = lruCache.head + if lruCache.head != nil { + lruCache.head.prev = node + } + lruCache.head = node + if lruCache.tail == nil { + lruCache.tail = node + lruCache.tail.next = nil + } +} + +// Remove define +func (lruCache *LRUCache) Remove(node *Node) { + if node == lruCache.head { + lruCache.head = node.next + if node.next != nil { + node.next.prev = nil + } + node.next = nil + return + } + if node == lruCache.tail { + lruCache.tail = node.prev + node.prev.next = nil + node.prev = nil + return + } + node.prev.next = node.next + node.next.prev = node.prev +} + +/** + * Your LRUCache object will be instantiated and called as such: + * obj := Constructor(capacity); + * param_1 := obj.Get(key); + * obj.Put(key,value); + */ + +// 22% +// import "container/list" + +// type LRUCache struct { +// Cap int +// Keys map[int]*list.Element +// List *list.List +// } + +// type pair struct { +// K, V int +// } + +// func Constructor(capacity int) LRUCache { +// return LRUCache{ +// Cap: capacity, +// Keys: make(map[int]*list.Element), +// List: list.New(), +// } +// } + +// func (c *LRUCache) Get(key int) int { +// if el, ok := c.Keys[key]; ok { +// c.List.MoveToFront(el) +// return el.Value.(pair).V +// } +// return -1 +// } + +// func (c *LRUCache) Put(key int, value int) { +// if el, ok := c.Keys[key]; ok { +// el.Value = pair{K: key, V: value} +// c.List.MoveToFront(el) +// } else { +// el := c.List.PushFront(pair{K: key, V: value}) +// c.Keys[key] = el +// } +// if c.List.Len() > c.Cap { +// el := c.List.Back() +// c.List.Remove(el) +// delete(c.Keys, el.Value.(pair).K) +// } +// } + +/** + * Your LRUCache object will be instantiated and called as such: + * obj := Constructor(capacity); + * param_1 := obj.Get(key); + * obj.Put(key,value); + */ diff --git a/template/SegmentTree.go b/template/SegmentTree.go new file mode 100644 index 000000000..e28db284f --- /dev/null +++ b/template/SegmentTree.go @@ -0,0 +1,265 @@ +package template + +// SegmentTree define +type SegmentTree struct { + data, tree, lazy []int + left, right int + merge func(i, j int) int +} + +// Init define +func (st *SegmentTree) Init(nums []int, oper func(i, j int) int) { + st.merge = oper + data, tree, lazy := make([]int, len(nums)), make([]int, 4*len(nums)), make([]int, 4*len(nums)) + for i := 0; i < len(nums); i++ { + data[i] = nums[i] + } + st.data, st.tree, st.lazy = data, tree, lazy + if len(nums) > 0 { + st.buildSegmentTree(0, 0, len(nums)-1) + } +} + +// ๅœจ treeIndex ็š„ไฝ็ฝฎๅˆ›ๅปบ [left....right] ๅŒบ้—ด็š„็บฟๆฎตๆ ‘ +func (st *SegmentTree) buildSegmentTree(treeIndex, left, right int) { + if left == right { + st.tree[treeIndex] = st.data[left] + return + } + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + st.buildSegmentTree(leftTreeIndex, left, midTreeIndex) + st.buildSegmentTree(rightTreeIndex, midTreeIndex+1, right) + st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) +} + +func (st *SegmentTree) leftChild(index int) int { + return 2*index + 1 +} + +func (st *SegmentTree) rightChild(index int) int { + return 2*index + 2 +} + +// ๆŸฅ่ฏข [left....right] ๅŒบ้—ดๅ†…็š„ๅ€ผ + +// Query define +func (st *SegmentTree) Query(left, right int) int { + if len(st.data) > 0 { + return st.queryInTree(0, 0, len(st.data)-1, left, right) + } + return 0 +} + +// ๅœจไปฅ treeIndex ไธบๆ น็š„็บฟๆฎตๆ ‘ไธญ [left...right] ็š„่Œƒๅ›ด้‡Œ๏ผŒๆœ็ดขๅŒบ้—ด [queryLeft...queryRight] ็š„ๅ€ผ +func (st *SegmentTree) queryInTree(treeIndex, left, right, queryLeft, queryRight int) int { + if left == queryLeft && right == queryRight { + return st.tree[treeIndex] + } + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + if queryLeft > midTreeIndex { + return st.queryInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) + } else if queryRight <= midTreeIndex { + return st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) + } + return st.merge(st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex), + st.queryInTree(rightTreeIndex, midTreeIndex+1, right, midTreeIndex+1, queryRight)) +} + +// ๆŸฅ่ฏข [left....right] ๅŒบ้—ดๅ†…็š„ๅ€ผ + +// QueryLazy define +func (st *SegmentTree) QueryLazy(left, right int) int { + if len(st.data) > 0 { + return st.queryLazyInTree(0, 0, len(st.data)-1, left, right) + } + return 0 +} + +func (st *SegmentTree) queryLazyInTree(treeIndex, left, right, queryLeft, queryRight int) int { + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + if left > queryRight || right < queryLeft { // segment completely outside range + return 0 // represents a null node + } + if st.lazy[treeIndex] != 0 { // this node is lazy + for i := 0; i < right-left+1; i++ { + st.tree[treeIndex] = st.merge(st.tree[treeIndex], st.lazy[treeIndex]) + // st.tree[treeIndex] += (right - left + 1) * st.lazy[treeIndex] // normalize current node by removing lazinesss + } + if left != right { // update lazy[] for children nodes + st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], st.lazy[treeIndex]) + st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], st.lazy[treeIndex]) + // st.lazy[leftTreeIndex] += st.lazy[treeIndex] + // st.lazy[rightTreeIndex] += st.lazy[treeIndex] + } + st.lazy[treeIndex] = 0 // current node processed. No longer lazy + } + if queryLeft <= left && queryRight >= right { // segment completely inside range + return st.tree[treeIndex] + } + if queryLeft > midTreeIndex { + return st.queryLazyInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) + } else if queryRight <= midTreeIndex { + return st.queryLazyInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) + } + // merge query results + return st.merge(st.queryLazyInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex), + st.queryLazyInTree(rightTreeIndex, midTreeIndex+1, right, midTreeIndex+1, queryRight)) +} + +// ๆ›ดๆ–ฐ index ไฝ็ฝฎ็š„ๅ€ผ + +// Update define +func (st *SegmentTree) Update(index, val int) { + if len(st.data) > 0 { + st.updateInTree(0, 0, len(st.data)-1, index, val) + } +} + +// ไปฅ treeIndex ไธบๆ น๏ผŒๆ›ดๆ–ฐ index ไฝ็ฝฎไธŠ็š„ๅ€ผไธบ val +func (st *SegmentTree) updateInTree(treeIndex, left, right, index, val int) { + if left == right { + st.tree[treeIndex] = val + return + } + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + if index > midTreeIndex { + st.updateInTree(rightTreeIndex, midTreeIndex+1, right, index, val) + } else { + st.updateInTree(leftTreeIndex, left, midTreeIndex, index, val) + } + st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) +} + +// ๆ›ดๆ–ฐ [updateLeft....updateRight] ไฝ็ฝฎ็š„ๅ€ผ +// ๆณจๆ„่ฟ™้‡Œ็š„ๆ›ดๆ–ฐๅ€ผๆ˜ฏๅœจๅŽŸๆฅๅ€ผ็š„ๅŸบ็ก€ไธŠๅขžๅŠ ๆˆ–่€…ๅ‡ๅฐ‘๏ผŒ่€Œไธๆ˜ฏๆŠŠ่ฟ™ไธชๅŒบ้—ดๅ†…็š„ๅ€ผ้ƒฝ่ต‹ๅ€ผไธบ x๏ผŒๅŒบ้—ดๆ›ดๆ–ฐๅ’Œๅ•็‚นๆ›ดๆ–ฐไธๅŒ +// ่ฟ™้‡Œ็š„ๅŒบ้—ดๆ›ดๆ–ฐๅ…ณๆณจ็š„ๆ˜ฏๅ˜ๅŒ–๏ผŒๅ•็‚นๆ›ดๆ–ฐๅ…ณๆณจ็š„ๆ˜ฏๅฎšๅ€ผ +// ๅฝ“็„ถๅŒบ้—ดๆ›ดๆ–ฐไนŸๅฏไปฅ้ƒฝๆ›ดๆ–ฐๆˆๅฎšๅ€ผ๏ผŒๅฆ‚ๆžœๅชๅŒบ้—ดๆ›ดๆ–ฐๆˆๅฎšๅ€ผ๏ผŒ้‚ฃไนˆ lazy ๆ›ดๆ–ฐ็ญ–็•ฅ้œ€่ฆๅ˜ๅŒ–๏ผŒmerge ็ญ–็•ฅไนŸ้œ€่ฆๅ˜ๅŒ–๏ผŒ่ฟ™้‡Œๆš‚ไธ่ฏฆ็ป†่ฎจ่ฎบ + +// UpdateLazy define +func (st *SegmentTree) UpdateLazy(updateLeft, updateRight, val int) { + if len(st.data) > 0 { + st.updateLazyInTree(0, 0, len(st.data)-1, updateLeft, updateRight, val) + } +} + +func (st *SegmentTree) updateLazyInTree(treeIndex, left, right, updateLeft, updateRight, val int) { + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + if st.lazy[treeIndex] != 0 { // this node is lazy + for i := 0; i < right-left+1; i++ { + st.tree[treeIndex] = st.merge(st.tree[treeIndex], st.lazy[treeIndex]) + //st.tree[treeIndex] += (right - left + 1) * st.lazy[treeIndex] // normalize current node by removing laziness + } + if left != right { // update lazy[] for children nodes + st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], st.lazy[treeIndex]) + st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], st.lazy[treeIndex]) + // st.lazy[leftTreeIndex] += st.lazy[treeIndex] + // st.lazy[rightTreeIndex] += st.lazy[treeIndex] + } + st.lazy[treeIndex] = 0 // current node processed. No longer lazy + } + + if left > right || left > updateRight || right < updateLeft { + return // out of range. escape. + } + + if updateLeft <= left && right <= updateRight { // segment is fully within update range + for i := 0; i < right-left+1; i++ { + st.tree[treeIndex] = st.merge(st.tree[treeIndex], val) + //st.tree[treeIndex] += (right - left + 1) * val // update segment + } + if left != right { // update lazy[] for children + st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], val) + st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], val) + // st.lazy[leftTreeIndex] += val + // st.lazy[rightTreeIndex] += val + } + return + } + st.updateLazyInTree(leftTreeIndex, left, midTreeIndex, updateLeft, updateRight, val) + st.updateLazyInTree(rightTreeIndex, midTreeIndex+1, right, updateLeft, updateRight, val) + // merge updates + st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) +} + +// SegmentCountTree define +type SegmentCountTree struct { + data, tree []int + left, right int + merge func(i, j int) int +} + +// Init define +func (st *SegmentCountTree) Init(nums []int, oper func(i, j int) int) { + st.merge = oper + + data, tree := make([]int, len(nums)), make([]int, 4*len(nums)) + for i := 0; i < len(nums); i++ { + data[i] = nums[i] + } + st.data, st.tree = data, tree +} + +// ๅœจ treeIndex ็š„ไฝ็ฝฎๅˆ›ๅปบ [left....right] ๅŒบ้—ด็š„็บฟๆฎตๆ ‘ +func (st *SegmentCountTree) buildSegmentTree(treeIndex, left, right int) { + if left == right { + st.tree[treeIndex] = st.data[left] + return + } + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + st.buildSegmentTree(leftTreeIndex, left, midTreeIndex) + st.buildSegmentTree(rightTreeIndex, midTreeIndex+1, right) + st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) +} + +func (st *SegmentCountTree) leftChild(index int) int { + return 2*index + 1 +} + +func (st *SegmentCountTree) rightChild(index int) int { + return 2*index + 2 +} + +// ๆŸฅ่ฏข [left....right] ๅŒบ้—ดๅ†…็š„ๅ€ผ + +// Query define +func (st *SegmentCountTree) Query(left, right int) int { + if len(st.data) > 0 { + return st.queryInTree(0, 0, len(st.data)-1, left, right) + } + return 0 +} + +// ๅœจไปฅ treeIndex ไธบๆ น็š„็บฟๆฎตๆ ‘ไธญ [left...right] ็š„่Œƒๅ›ด้‡Œ๏ผŒๆœ็ดขๅŒบ้—ด [queryLeft...queryRight] ็š„ๅ€ผ๏ผŒๅ€ผๆ˜ฏ่ฎกๆ•ฐๅ€ผ +func (st *SegmentCountTree) queryInTree(treeIndex, left, right, queryLeft, queryRight int) int { + if queryRight < st.data[left] || queryLeft > st.data[right] { + return 0 + } + if queryLeft <= st.data[left] && queryRight >= st.data[right] || left == right { + return st.tree[treeIndex] + } + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + return st.queryInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) + + st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) +} + +// ๆ›ดๆ–ฐ่ฎกๆ•ฐ + +// UpdateCount define +func (st *SegmentCountTree) UpdateCount(val int) { + if len(st.data) > 0 { + st.updateCountInTree(0, 0, len(st.data)-1, val) + } +} + +// ไปฅ treeIndex ไธบๆ น๏ผŒๆ›ดๆ–ฐ [left...right] ๅŒบ้—ดๅ†…็š„่ฎกๆ•ฐ +func (st *SegmentCountTree) updateCountInTree(treeIndex, left, right, val int) { + if val >= st.data[left] && val <= st.data[right] { + st.tree[treeIndex]++ + if left == right { + return + } + midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) + st.updateCountInTree(rightTreeIndex, midTreeIndex+1, right, val) + st.updateCountInTree(leftTreeIndex, left, midTreeIndex, val) + } +} diff --git a/template/UnionFind.go b/template/UnionFind.go new file mode 100644 index 000000000..a5995a5af --- /dev/null +++ b/template/UnionFind.go @@ -0,0 +1,134 @@ +package template + +// UnionFind defind +// ่ทฏๅพ„ๅŽ‹็ผฉ + ็งฉไผ˜ๅŒ– +type UnionFind struct { + parent, rank []int + count int +} + +// Init define +func (uf *UnionFind) Init(n int) { + uf.count = n + uf.parent = make([]int, n) + uf.rank = make([]int, n) + for i := range uf.parent { + uf.parent[i] = i + } +} + +// Find define +func (uf *UnionFind) Find(p int) int { + root := p + for root != uf.parent[root] { + root = uf.parent[root] + } + // compress path + for p != uf.parent[p] { + tmp := uf.parent[p] + uf.parent[p] = root + p = tmp + } + return root +} + +// Union define +func (uf *UnionFind) Union(p, q int) { + proot := uf.Find(p) + qroot := uf.Find(q) + if proot == qroot { + return + } + if uf.rank[qroot] > uf.rank[proot] { + uf.parent[proot] = qroot + } else { + uf.parent[qroot] = proot + if uf.rank[proot] == uf.rank[qroot] { + uf.rank[proot]++ + } + } + uf.count-- +} + +// TotalCount define +func (uf *UnionFind) TotalCount() int { + return uf.count +} + +// UnionFindCount define +// ่ฎก็ฎ—ๆฏไธช้›†ๅˆไธญๅ…ƒ็ด ็š„ไธชๆ•ฐ + ๆœ€ๅคง้›†ๅˆๅ…ƒ็ด ไธชๆ•ฐ +type UnionFindCount struct { + parent, count []int + maxUnionCount int +} + +// Init define +func (uf *UnionFindCount) Init(n int) { + uf.parent = make([]int, n) + uf.count = make([]int, n) + for i := range uf.parent { + uf.parent[i] = i + uf.count[i] = 1 + } +} + +// Find define +func (uf *UnionFindCount) Find(p int) int { + root := p + for root != uf.parent[root] { + root = uf.parent[root] + } + return root +} + +// ไธ่ฟ›่กŒ็งฉๅŽ‹็ผฉ๏ผŒๆ—ถ้—ดๅคๆ‚ๅบฆ็ˆ†็‚ธ๏ผŒๅคช้ซ˜ไบ† +// func (uf *UnionFindCount) union(p, q int) { +// proot := uf.find(p) +// qroot := uf.find(q) +// if proot == qroot { +// return +// } +// if proot != qroot { +// uf.parent[proot] = qroot +// uf.count[qroot] += uf.count[proot] +// } +// } + +// Union define +func (uf *UnionFindCount) Union(p, q int) { + proot := uf.Find(p) + qroot := uf.Find(q) + if proot == qroot { + return + } + if proot == len(uf.parent)-1 { + //proot is root + } else if qroot == len(uf.parent)-1 { + // qroot is root, always attach to root + proot, qroot = qroot, proot + } else if uf.count[qroot] > uf.count[proot] { + proot, qroot = qroot, proot + } + + //set relation[0] as parent + uf.maxUnionCount = max(uf.maxUnionCount, (uf.count[proot] + uf.count[qroot])) + uf.parent[qroot] = proot + uf.count[proot] += uf.count[qroot] +} + +// Count define +func (uf *UnionFindCount) Count() []int { + return uf.count +} + +// MaxUnionCount define +func (uf *UnionFindCount) MaxUnionCount() int { + return uf.maxUnionCount +} + +func max(a int, b int) int { + if a > b { + return a + } + return b +} diff --git a/template/bucket.go b/template/bucket.go new file mode 100644 index 000000000..ac9ab9289 --- /dev/null +++ b/template/bucket.go @@ -0,0 +1,55 @@ +package template + +import ( + "container/list" + "sync" +) + +type bucket struct { + sync.RWMutex + keys map[string]*list.Element +} + +func (b *bucket) pairCount() int { + b.RLock() + defer b.RUnlock() + return len(b.keys) +} + +func (b *bucket) get(key string) *list.Element { + b.RLock() + defer b.RUnlock() + if el, ok := b.keys[key]; ok { + return el + } + return nil +} + +func (b *bucket) set(key string, value interface{}) (*list.Element, *list.Element) { + el := &list.Element{Value: Pair{key: key, value: value, cmd: PushFront}} + b.Lock() + exist := b.keys[key] + b.keys[key] = el + b.Unlock() + return el, exist +} + +func (b *bucket) update(key string, el *list.Element) { + b.Lock() + b.keys[key] = el + b.Unlock() +} + +func (b *bucket) delete(key string) *list.Element { + b.Lock() + el := b.keys[key] + delete(b.keys, key) + b.Unlock() + return el +} + +func (b *bucket) clear() { + b.Lock() + b.keys = make(map[string]*list.Element) + b.Unlock() +} diff --git a/template/index.html b/template/index.html new file mode 100644 index 000000000..718f4e8b9 --- /dev/null +++ b/template/index.html @@ -0,0 +1,3805 @@ + + + + + + + Template ยท Kimi's LeetcodeGolang Notes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      + + + + + + + + +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                                                      來源

                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      © Kimi Tsai all right reserved.            Updated : 2024-03-24 07:13:39
                                                                                                                                                                                                                                                      + + +
                                                                                                                                                                                                                                                      + +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                      + +

                                                                                                                                                                                                                                                      results matching ""

                                                                                                                                                                                                                                                      +
                                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                                        + +

                                                                                                                                                                                                                                                        No results matching ""

                                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                                        +
                                                                                                                                                                                                                                                        + +
                                                                                                                                                                                                                                                        + + + + + + + + + + + + + + +
                                                                                                                                                                                                                                                        + + +
                                                                                                                                                                                                                                                        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +