问题如下:
给定一个整数数组 nums 和一个整数 val,删除 nums 中所有出现的 val 就地。元素的顺序可以改变。然后返回 nums 中不等于 val.
的元素个数考虑 nums 中不等于 val 的元素数量为 k,要被接受,您需要执行以下操作:
自定义法官:
法官将使用以下代码测试您的解决方案:
int[] nums = [...]; // Input array int val = ...; // Value to remove int[] expectedNums = [...]; // The expected answer with correct length. // It is sorted with no values equaling val. int k = removeElement(nums, val); // Calls your implementation assert k == expectedNums.length; sort(nums, 0, k); // Sort the first k elements of nums for (int i = 0; i < actualLength; i++) { assert nums[i] == expectedNums[i]; }
如果所有断言都通过,那么您的解决方案将被接受。
示例1:
Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2,_,_] Explanation: Your function should return k = 2, with the first two elements of nums being 2. It does not matter what you leave beyond the returned k (hence they are underscores).
示例2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3,_,_,_] Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. Note that the five elements can be returned in any order. It does not matter what you leave beyond the returned k (hence they are underscores).
这是我解决的方法:
为了解决这个问题,我使用了两个主要策略:
class Solution: def removeElement(self, nums: List[int], val: int) -> int: k = 0
for i in range(len(nums)): if nums[i] != val: nums[k] = nums[i] k += 1
return k
这是完整的解决方案:
class Solution: def removeElement(self, nums: List[int], val: int) -> int: k = 0 for i in range(len(nums)): if nums[i] != val: nums[k] = nums[i] k += 1 return k
以上是Leetcode Day 删除元素解释的详细内容。更多信息请关注PHP中文网其他相关文章!