数组-双指针

1. 双指针

双指针应用时,需要创建虚拟节点,这样可以避免第一个元素进行特殊处理。

思路:快指针正常向前,慢指针在某些情况下向前。

例如:leetcode 27, 删除数组中等于val元素,返回数组长度,

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        pre = -1
        next = 0
        dup = 0
        while next < len(nums):
            if nums[next] == val:
                dup += 1
            else:
                nums[pre + 1] = nums[next]
                pre += 1
            next += 1
        return len(nums) - dup

2. 有序数组移除重复的元素

题目:leetcode 80

2.1 题目描述

# Given an integer array nums sorted in non-decreasing order, remove some 
# duplicates in-place such that each unique element appears at most twice. The relative 
# order of the elements should be kept the same. 
# 
#  Since it is impossible to change the length of the array in some languages, 
# you must instead have the result be placed in the first part of the array nums. 
# More formally, if there are k elements after removing the duplicates, then the 
# first k elements of nums should hold the final result. It does not matter what 
# you leave beyond the first k elements. 
# 
#  Return k after placing the final result in the first k slots of nums. 
# 
#  Do not allocate extra space for another array. You must do this by modifying 
# the input array in-place with O(1) extra memory. 
# 
#  Custom Judge: 
# 
#  The judge will test your solution with the following code: 
# 
#  
# int[] nums = [...]; // Input array
# int[] expectedNums = [...]; // The expected answer with correct length
# 
# int k = removeDuplicates(nums); // Calls your implementation
# 
# assert k == expectedNums.length;
# for (int i = 0; i < k; i++) {
#     assert nums[i] == expectedNums[i];
# }
#  
# 
#  If all assertions pass, then your solution will be accepted. 
# 
#  
#  Example 1: 
# 
#  
# Input: nums = [1,1,1,2,2,3]
# Output: 5, nums = [1,1,2,2,3,_]
# Explanation: Your function should return k = 5, with the first five elements 
# of nums being 1, 1, 2, 2 and 3 respectively.
# It does not matter what you leave beyond the returned k (hence they are 
# underscores).
#  
# 
#  Example 2: 
# 
#  
# Input: nums = [0,0,1,1,1,1,2,3,3]
# Output: 7, nums = [0,0,1,1,2,3,3,_,_]
# Explanation: Your function should return k = 7, with the first seven elements 
# of nums being 0, 0, 1, 1, 2, 3 and 3 respectively.
# It does not matter what you leave beyond the returned k (hence they are 
# underscores).
#  
# 
#  
#  Constraints: 
# 
#  
#  1 <= nums.length <= 3 * 10⁴ 
#  -10⁴ <= nums[i] <= 10⁴ 
#  nums is sorted in non-decreasing order. 
#  

2.2 实现代码

# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        k = 2
        i = 0
        j = 0
        while j < len(nums):
            if i < k or nums[i - k] != nums[j]:
                nums[i] = nums[j]
                i += 1
            j += 1
        return i


# leetcode submit region end(Prohibit modification and deletion)

if __name__ == '__main__':
    so = Solution()
    nums = [1, 1, 1, 2, 2, 3]
    res = so.removeDuplicates(nums)
    print(nums[:res])

2.3 解题思路

  • 双指针策略,快指针正常移动,慢指针在特定的条件下移动。
  • 慢指针移动的条件,慢指针<k慢指针-k==快指针的元素
  • 满足慢指针移动的条件时,慢指针要进行赋值操作。

3 最后一个单词的长度

# Given a string s consisting of words and spaces, return the length of the 
# last word in the string. 
# 
#  A word is a maximal substring consisting of non-space characters only. 
# 
#  
#  Example 1: 
# 
#  
# Input: s = "Hello World"
# Output: 5
# Explanation: The last word is "World" with length 5.
#  
# 
#  Example 2: 
# 
#  
# Input: s = "   fly me   to   the moon  "
# Output: 4
# Explanation: The last word is "moon" with length 4.
#  
# 
#  Example 3: 
# 
#  
# Input: s = "luffy is still joyboy"
# Output: 6
# Explanation: The last word is "joyboy" with length 6.
#  
# 
#  
#  Constraints: 
# 
#  
#  1 <= s.length <= 10⁴ 
#  s consists of only English letters and spaces ' '. 
#  There will be at least one word in s. 
#  
#  Related Topics 字符串 👍 583 👎 0


# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        left = right = len(s) - 1
        flag = True
        while left >= 0:
            if flag and s[left] != " ":
                flag = False
                right = left
            if not flag and s[left] == " ":
                break
            left -= 1
        return len(s[left + 1:right + 1])


# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
    s = "   fly me   to   the moon  "
    so = Solution()
    res = so.lengthOfLastWord(s)
    print(res)
  • left为快指针,right为慢指针,当快指针不满足条件时,慢指针向前移动。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值