題目:Remove Element
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
給一個數組和一個目標值,返回從數組中刪除目標值之後的剩餘長度
例如:
輸入:[3,2,2,3] 2
輸出:2
思路
暴力解決,循環查找目標值,然後刪除
code
func removeElement(nums []int, val int) int {
if nums == nil {
return 0
}
for i := 0; i < len(nums); {
if nums[i] == val {
nums = append(nums[:i], nums[i+1:]...)
i--
}
i++
}
return len(nums)
}
更多內容請移步我的repo:https://github.com/anakin/golang-leetcode
閱讀更多 anakinsun 的文章