- 移除元素
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/remove-element
class Solution(object):
def removeElement(self, nums, val):
idx_new = 0
for idx in range(len(nums)):
if nums[idx] != val:
nums[idx_new] = nums[idx]
idx_new += 1
return idx_new
双指针:idx 和 idx_new
- 删除有序数组中的重复项
class Solution(object):
def removeDuplicates(self, nums):
idx_new = 1
for idx in range(len(nums)-1):
if nums[idx+1] != nums[idx]:
nums[idx_new] = nums[idx + 1]
idx_new += 1
return idx_new
- 移动零——双指针+快排
将非零元素按双指针向前排列,其他元素赋0
class Solution(object):
def moveZeroes(self, nums):
idx_new = 0
for idx in range(len(nums)):
if nums[idx] != 0:
nums[idx_new] = nums[idx]
idx_new += 1
for i in range(idx_new,len(nums)):
nums[i] = 0
return nums
快速排列解法:
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
if not nums:
return 0
# 两个指针i和j
j = 0
for i in xrange(len(nums)):
# 当前元素!=0,就把其交换到左边,等于0的交换到右边
if nums[i]:
nums[j],nums[i] = nums[i],nums[j]
j += 1
作者:wang_ni_ma
链接:https://leetcode.cn/problems/move-zeroes/solution/dong-hua-yan-shi-283yi-dong-ling-by-wang_ni_ma/
来源:力扣(LeetCode)
- 比较含退格的字符串(实现较难)
class Solution(object):
def backspaceCompare(self, s, t):
idx_s,idx_t = len(s)-1,len(t)-1
count_s = count_t = 0
while idx_s >=0 or idx_t >=0:
while idx_s >= 0:
if s[idx_s] == '#':
count_s += 1
idx_s -= 1
elif (s[idx_s] != '#') and (count_s != 0):
count_s -= 1
idx_s -= 1
else:
break
while idx_t >= 0:
if t[idx_t] == '#':
count_t += 1
idx_t -= 1
elif (t[idx_t] != '#') and (count_t != 0):
count_t -= 1
idx_t -= 1
else:
break
if idx_s>=0 and idx_t>=0:
if s[idx_s] != t[idx_t]:
return False
elif idx_s>=0 or idx_t>=0:
return False
idx_t -= 1
idx_s -= 1
return True
考虑里层循环结束以后指针指向负数的情况。