题干懒人包
输入一个数组及一个数,最后输出一个数值代表非重複数值的数量,然后以下几点要注意:
只能修改该数组,利用的空间複杂度最多为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 isolution = 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 = 3Output: 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.