Skip to content

Commit

Permalink
🎨27.移除元素
Browse files Browse the repository at this point in the history
  • Loading branch information
techoc committed May 13, 2024
1 parent 6ce77ed commit c5a84d8
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 28 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
- [20.有效的括号](leetcode/easy/20.go)
- [21.合并两个有序链表](leetcode/easy/21.go)
- [26.删除有序数组中的重复项](leetcode/easy/t26/solution.go)
- [27.移除元素](leetcode/easy/27.go)
- [27.移除元素](leetcode/easy/t27/solution.go)
- [28.实现 strStr()](leetcode/easy/28.go)
- [35.搜索插入位置](leetcode/easy/35.go)
- [53.最大子序和](leetcode/easy/53.go)
Expand Down
27 changes: 0 additions & 27 deletions leetcode/easy/27.go

This file was deleted.

15 changes: 15 additions & 0 deletions leetcode/easy/t27/solution.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package t27

// 27. 移除元素
// https://leetcode.cn/problems/remove-element
func removeElement(nums []int, val int) int {
slow, fast := 0, 0
for fast < len(nums) {
if nums[fast] != val { // 快指针不等于移除元素时 交换快慢指针的值 慢指针前进·
nums[slow] = nums[fast]
slow++
}
fast++
}
return slow
}
32 changes: 32 additions & 0 deletions leetcode/easy/t27/solution_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package t27

import "testing"

func TestRemoveElement(t *testing.T) {
tests := []struct {
name string
nums []int
val int
expect int
}{
{
name: "case 1",
nums: []int{3, 2, 2, 3},
val: 3,
expect: 2,
},
{
name: "case 2",
nums: []int{0, 1, 2, 2, 3, 0, 4, 2},
val: 2,
expect: 5,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := removeElement(tt.nums, tt.val); got != tt.expect {
t.Errorf("removeElement() = %v, want %v", got, tt.expect)
}
})
}
}

0 comments on commit c5a84d8

Please sign in to comment.