LeetCode 27 Remove Element 移除元素给定一个数组 nums 和一个值 val你需要原地移除所有数值等于 val 的元素返回移除后数组的新长度。Given an array nums and a value val, remove all instances of that value in-place and return the new length.Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.The order of elements can be changed. It doesn’t matter what you leave beyond the new length.Example 1:Given nums [3,2,2,3], val 3,Your function should return length 2, with the first twoelements of nums being2.It doesn’t matter what you leave beyond the returned length.class Solution 1:def removeElement(self, nums: List[int], val: int) - int: while val in nums: nums.remove(val) return len(nums)class Solution 2:def removeElement(self, nums: List[int], val: int) - int: i 0 for num in nums: if num ! val: nums[i] num i 1 return i单向遍历数组元素遍历到的元素值不等于val则从左到右依次填充覆盖nums列表如果发现等于val了则位置留着给后面不等于val的值填充。所以最后nums[i]前面是剔除等于val值排列的后面则还是nums原来的值。class Solution 3:def removeElement(self, nums, val): i 0 j len(nums) - 1 while i j: if nums[i] val: nums[i], nums[j] nums[j], nums[i] j - 1 else: i 1 return j 1双向遍历数组元素如果左边元素nums[i]值等于val则num[j]和num[i]值交换j-1往左一步num[i]再和val比较如果值等于val则num[j]和num[i]值再交换并且j往前一步否则i往后一步。所以最后num[j]后面元素值全部都等于val前面的为不等于val的。leetcode - remove element力扣 - 移除元素
LeetCode | 一只数据媛的刷题笔记(1)
LeetCode 27 Remove Element 移除元素给定一个数组 nums 和一个值 val你需要原地移除所有数值等于 val 的元素返回移除后数组的新长度。Given an array nums and a value val, remove all instances of that value in-place and return the new length.Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.The order of elements can be changed. It doesn’t matter what you leave beyond the new length.Example 1:Given nums [3,2,2,3], val 3,Your function should return length 2, with the first twoelements of nums being2.It doesn’t matter what you leave beyond the returned length.class Solution 1:def removeElement(self, nums: List[int], val: int) - int: while val in nums: nums.remove(val) return len(nums)class Solution 2:def removeElement(self, nums: List[int], val: int) - int: i 0 for num in nums: if num ! val: nums[i] num i 1 return i单向遍历数组元素遍历到的元素值不等于val则从左到右依次填充覆盖nums列表如果发现等于val了则位置留着给后面不等于val的值填充。所以最后nums[i]前面是剔除等于val值排列的后面则还是nums原来的值。class Solution 3:def removeElement(self, nums, val): i 0 j len(nums) - 1 while i j: if nums[i] val: nums[i], nums[j] nums[j], nums[i] j - 1 else: i 1 return j 1双向遍历数组元素如果左边元素nums[i]值等于val则num[j]和num[i]值交换j-1往左一步num[i]再和val比较如果值等于val则num[j]和num[i]值再交换并且j往前一步否则i往后一步。所以最后num[j]后面元素值全部都等于val前面的为不等于val的。leetcode - remove element力扣 - 移除元素