LC 27, 26, 283, 844, 977 - Array Remove Items

LC 27, 26, 283, 844, 977

LC 27

Remove the elem from a list (array). The intuitive approach is to use list methods like remove, pop. However, noted that the list.remove(val) only removes the first val from the list which matches the specified value, and list.pop(N) takes time O(n), where list.pop() takes time O(1).

代码随想录 - 27. 移除元素

# lc 704
def remove_element(self, nums: List[int], val: int) -> int:
    slow_ind = 0
    for fast_ind in range(len(nums)):
        if nums[fast_ind] != val:
            nums[slow_ind] = nums[fast_ind]
            slow_ind += 1
    return slow_ind

Logic

  • Duo pointers methods: Credit to Carl.
    • fast_ind points to the value in the original list,
    • slow_ind points to the new index that is supposed to be place the old elem.
  • Overwrite happens only if the fast_ind points to the value that is not removed. Meanwhile, the next index, slow_ind, is updated.

LC 26

26. Remove Duplicates from Sorted Array

Logic

  • Analogue to LC27, but change the overwrite condition to nums[fast_ind] != nums[fast_ind - 1].

Other approaches

  1. Intuitive but not stable:
nums[:] = list(set(nums))
return len(nums)
  1. stable:
nums[:] = list(dict.fromkeys(nums))
return len(nums)

LC 283

283. Move Zeroes

Logic:

  • Analogue to LC 27, consider 0 as the elem to be removed.
  • After moving forward other elems, use nums[slow:] = [0] * (len(nums) - slow) to overwrite the rest of the list.

LC 844

844. Backspace String Compare

Logic:

  • Haven’t figured out how to do this with duo ptr yet.
    • The intuition gives:
if nums[fast] == "#":
	slow -= 1
else:
	keep the same way...

Not sure…

  • My approach:
    • Since python don’t allow to change string by indexing.
      • .append(val) when not “#”, backspace
      • .pop() when is a backspace
    • works like a charm.

LC 977

977. Squares of a Sorted Array

  1. intuitive:
    map(square, nums)
    nums.sort()
    
    which gives a time complexity O(n log n), thanks to the sorting.
  2. Cases division and merge:
	neg_lst = [negative values in nums]
	pos_lst = [positive values in nums]
	map(square, neg_lst)
	map(square, pos_lst)
	neg_lst.reverse()

	return merge(neg_lst, pos_lst)

Logic:

  • merge keep the returned list in non-decreasing order.

Summary:

  • Duo ptr is the GOD! hhh
  • On other questions, I was just going with the first-site thoughts.
  • Study period: EST 13PM - 16PM, 3hrs.

PS:

  • Conditions for using duo ptrs:
    • Change the treversing order, see LC 977.
    • Slow, fast ptr, where two ptr are representing the different states of the system, see LC 27.
    • TBD…
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值