Skip to content

Commit

Permalink
Resolved lc1679 way II
Browse files Browse the repository at this point in the history
  • Loading branch information
YuanData committed Oct 10, 2023
1 parent a475fdb commit 0e2a0da
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"testing"
)

func maxOperations(nums []int, k int) int {
func maxOperationsMap(nums []int, k int) int {

// 初始化答案為0
ans := 0
Expand Down Expand Up @@ -48,7 +48,7 @@ func maxOperations(nums []int, k int) int {
return ans
}

func TestMaxOperations(t *testing.T) {
func TestMaxOperationsMap(t *testing.T) {
tests := []struct {
nums []int
k int
Expand All @@ -61,7 +61,7 @@ func TestMaxOperations(t *testing.T) {
}

for _, test := range tests {
got := maxOperations(test.nums, test.k)
got := maxOperationsMap(test.nums, test.k)
if got != test.want {
t.Errorf("maxOperations(%v, %v) = %v; want %v", test.nums, test.k, got, test.want)
}
Expand Down
49 changes: 49 additions & 0 deletions lc/lc1679MaxNumberofK-SumPairsBySort_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package lc

import (
"sort"
"testing"
)

func maxOperationsSort(nums []int, k int) int {
sort.Ints(nums) // 先排序
left, right := 0, len(nums)-1 // 使用左右指針
operations := 0

for left < right {
currentSum := nums[left] + nums[right]

// 如果當前和等於k,則找到一對,左右指針都要移動
if currentSum == k {
operations++
left++
right--
} else if currentSum < k { // 如果當前和小於k,則左指針向右移動,使得和增加
left++
} else { // 如果當前和大於k,則右指針向左移動,使得和減少
right--
}
}

return operations
}

func TestMaxOperationsSort(t *testing.T) {
tests := []struct {
nums []int
k int
want int
}{
{[]int{1, 2, 3, 4}, 5, 2},
{[]int{3, 1, 3, 4, 3}, 6, 1},
{[]int{2, 5, 4, 4, 1, 3, 4, 4, 1, 4, 4, 1, 2, 1, 2, 2, 3, 2, 4, 2}, 3, 4},
// 更多的測試案例...
}

for _, test := range tests {
got := maxOperationsSort(test.nums, test.k)
if got != test.want {
t.Errorf("maxOperations(%v, %v) = %v; want %v", test.nums, test.k, got, test.want)
}
}
}

0 comments on commit 0e2a0da

Please sign in to comment.