力扣hot100_技巧_python版本

一、136. 只出现一次的数字

  • 思路:
    • 任何数和 0 做异或运算,结果仍然是原来的数,即 a⊕0=a。
    • 任何数和其自身做异或运算,结果是 0,即 a⊕a=0。
    • 异或运算满足交换律和结合律,即 a⊕b⊕a=b⊕a⊕a=b⊕(a⊕a)=b⊕0=b。
  • 代码:
python 复制代码
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(xor, nums)

二、169. 多数元素

  • 代码:
python 复制代码
class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        n = len(nums)
        value_counts = defaultdict(int)
        for i in nums:
            value_counts[i] += 1
        for i in value_counts:
            if value_counts[i] >= n/2:
                return i

三、75. 颜色分类

  • 思路:
    两次遍历,第一次将所有的0归为,第二次将所有的1归为
  • 代码:
python 复制代码
class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        def swap(i, j):
            nums[i], nums[j] = nums[j], nums[i]
        n = len(nums)
        ptr = 0
        for i in range(n):
            if nums[i] == 0:
                swap(i, ptr)
                ptr += 1
        for i in range(n):
            if nums[i] == 1:
                swap(i, ptr)
                ptr += 1  

四、31. 下一个排列

  • 代码:
python 复制代码
class Solution:
    def nextPermutation(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        i = n-2
        while i >= 0 and nums[i] >= nums[i+1]:
            i -= 1
        
        if i >= 0:
            j = n-1
            while nums[j] <= nums[i]:
                j -= 1
            nums[i], nums[j] = nums[j], nums[i]
        
        left, right = i+1, n-1
        while left<right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1

五、287. 寻找重复数

python 复制代码
class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        n, i = len(nums), 0
        while i < n:
            t, idx = nums[i], nums[i] - 1  # t 是当前值,idx 是当前值该放到的位置
            if nums[idx] == t:             # 如果当前值已经在它该在的位置上
                if idx != i:               # 表示当前值 t 和它"应该在的位置"的值相等,说明有重复,立即返回
                    return t
                i += 1
            else:
                nums[i], nums[idx] = nums[idx], nums[i]
        return -1
相关推荐
Wo3Shi4七11 分钟前
数组
数据结构·算法·go
前端付豪16 分钟前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
CoovallyAIHub18 分钟前
YOLOv13都来了,目标检测还卷得动吗?别急,还有这些新方向!
深度学习·算法·计算机视觉
这里有鱼汤21 分钟前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
北方有星辰zz24 分钟前
数据结构:栈
java·开发语言·数据结构
源码站~32 分钟前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐
MessiGo37 分钟前
Python 爬虫实战 | 国家医保
python
我是唐青枫1 小时前
C#.NET NLog 详解
开发语言·c#·.net
转转技术团队1 小时前
边学边做:图片识别技术的学习与应用
后端·算法
chanalbert1 小时前
Spring 6 源码深度掘金:66+核心原理与高频面试攻坚指南
python·spring·面试