Problem: 27. 移除元素
思路
设deleted
为左指针,available
为右指针,令deleted
从左至右找第一个待删除的值,令available
从右至左找第一个需要保留的值,将available
的值覆盖到deleted
上,此时即完成了一次逻辑删除
重复该操作直至available<=deleted
,此时有效子数组的末尾索引即为available
,由于需要返回数组长度,因此返回available+1
复杂度
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { fun removeElement(nums: IntArray, `val`: Int): Int { var deleted = 0 var available = nums.size - 1 while (deleted <= available) { while (deleted < nums.size && nums[deleted] != `val`) { deleted++ }
while (available >= 0 && nums[available] == `val`) { available-- }
if (available <= deleted) { break }
nums[deleted++] = nums[available--] } return available + 1 } }
|