力扣前200题|Day1-双指针简单题

26.删除有序数组中的重复数

  • 典型的快慢指针题目
class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        N = len(nums)
        slow,fast = 0,0
        while(fast<N):
            if nums[fast]==nums[slow]:
                fast += 1
            else:
                slow += 1
                nums[slow] = nums[fast]
                fast += 1
        return slow + 1

按思路写出来之后,看出来可以进行代码简化

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        N = len(nums)
        slow,fast = 0,0
        while(fast<N):
            if nums[fast]!=nums[slow]:
                slow += 1
                nums[slow] = nums[fast]
            fast += 1
        return slow + 1

88.合并两个有序数组

  • 题目要求原地修改nums1,由于nums1的后半段是空的,所以考虑逆向双指针!!! ,这是本题的关键点。逆向思维很重要。
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        index1,index2,ind = m-1,n-1,m+n-1
        while(ind>=0 and index1>=0 and index2>=0): ##直到某一方遍历完
            if nums1[index1]<nums2[index2]:
                nums1[ind] = nums2[index2]
                index2 -= 1
            else:
                nums1[ind] = nums1[index1]
                index1 -= 1
            ind -= 1
        if index2>=0: #如果是nums2没遍历完需要进行全部替换。而nums1本身就是结果数组,如果nums1没遍历完,则不用替换
            nums1[:ind+1] = nums2[:index2+1]
        return 

125.验证回文串

  • 左右指针,比较简单。注意题目是包括了数字字符的,最开始没注意,在包含数字的示例出错了
  • while判断超界这个问题也需要注意
class Solution:
    def isPalindrome(self, s: str) -> bool:
        def judgeA(alpha):
            asc = ord(alpha)
            if asc >= ord('A') and asc <= ord('Z'):
                return asc + 32
            elif (asc >= ord('a') and asc <= ord('z')) or (asc >= ord('0') and asc <= ord('9')):
                return asc
            else:
                return False
        
        left,right = 0,len(s)-1
        while(left<right):
            while(left<len(s)-1 and judgeA(s[left])==False): ## 注意在while里面判断不要超界!!!
                left += 1
            while(right>0 and judgeA(s[right])==False):
                right -= 1
            if judgeA(s[left])!=judgeA(s[right]):
                return False
            left += 1
            right -= 1

        return True

141.环形链表

  • 快慢指针,两倍速。 142这个题查找环的入口
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow,fast = head,head
        while(fast and fast.next):
            fast = fast.next.next
            slow = slow.next
            if slow==fast:
                return True
        return False

202.快乐数

  • 解法1,暴力循环
  • 解法2,如果不是快乐数,那么必定存在环,使得其不能为1。
  • 解法3,哈希表存储出现过的数。如果不是快乐数,出现的重复数字不为1。
#解法1 暴力解法
class Solution:
    def isHappy(self, n: int) -> bool:
        def square(num):
            res = 0
            while(num):
                res += (num%10)*(num%10)
                num = num//10
            return res
        N = 99
        for i in range(N):
            res = square(n)
            n = res
            if res==1:
                return True
        return False
#解法2,快慢指针判断环的存在--是否快乐数

```python
class Solution:
    def isHappy(self, n: int) -> bool:
        def square(num):
            res = 0
            while(num):
                res += (num%10)*(num%10)
                num = num//10
            return res
        slow = square(n)
        fast = square(square(n))
        while(slow!=fast):
            slow = square(slow)
            fast = square(square(fast))
        return slow==1
# 解法3,哈希表判断有没有重复数字
class Solution:
    def isHappy(self, n: int) -> bool:
        def square(num):
            res = 0
            while(num):
                res += (num%10)*(num%10)
                num = num//10
            return res
        dicts = {}
        while(n not in dicts.keys()):
            dicts[n] = 1
            n = square(n)
        return n==1

234.回文链表

  • 解法一,遍历链表保存值到数组,快慢指针判断回文
  • 解法二,两倍速遍历链表得到中间点,从链表中间开始对链表逆序,再从两边进行判断回文
##
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        vals = []
        while(head):
            vals.append(head.val)
            head = head.next
        left,right = 0,len(vals)-1
        while(left<right):
            if vals[left]!=vals[right]:
                return False
            left += 1
            right -= 1
        return True

283.移动零

  • 跟之前某个题很像,移除多余元素那个题,双指针交换两个数即可
class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        slow,fast = 0,0
        N = len(nums)
        while(fast<N):
            if nums[fast]!=0:
                nums[slow],nums[fast]=nums[fast],nums[slow]
                slow += 1
            fast+=1
        return 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值