-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
48 additions
and
28 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} | ||
} |