輸入一個數組及一個數,最後輸出一個數值代表非重複數值的數量,然後以下幾點要注意:
只能修改該數組,利用的空間複雜度最多為1(意思就是不能創建新的數組append值)
不用管超過回傳值以後nums的值
"""
比方說輸入的 nums = [0,1,2,2,3,0,4,2], val = 2
那最後回傳值要等於五,且 nums[:5] 要包含 0, 1, 2, 3, 4 這幾個數字,然後數字在該切片裡的順序不重要
"""
遍歷數組,把跟 val 一樣的元素進行交換,用 i 移動然後 tail 標記非重複跟重複交界
class Solution:
def removeElement(self, nums, val: int) -> int:
i = 0
tail = len(nums) - 1
while i <= tail:
if nums[i] != val:
i += 1
else:
nums[i], nums[tail] = nums[tail], nums[i]
tail -= 1
return i
solution = Solution()
print(solution.removeElement([2, 2, 3, 3], 3))
因為此題幹不需要知道nums後面接著是甚麼,所以這裡不用交換(上面其實也可以不用)。
class Solution(object):
def removeElement(self, nums, val):
j = 0
for i in nums:
if i != val:
nums[j] = i
j += 1
return j
這裡有提到
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: 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. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.