力扣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
相关推荐
铁蛋AI编程实战1 分钟前
通义千问 3.5 Turbo GGUF 量化版本地部署教程:4G 显存即可运行,数据永不泄露
java·人工智能·python
HyperAI超神经6 分钟前
在线教程|DeepSeek-OCR 2公式/表格解析同步改善,以低视觉token成本实现近4%的性能跃迁
开发语言·人工智能·深度学习·神经网络·机器学习·ocr·创业创新
jiang_changsheng14 分钟前
RTX 2080 Ti魔改22GB显卡的最优解ComfyUI教程
python·comfyui
R_.L16 分钟前
【QT】常用控件(按钮类控件、显示类控件、输入类控件、多元素控件、容器类控件、布局管理器)
开发语言·qt
Zach_yuan25 分钟前
自定义协议:实现网络计算器
linux·服务器·开发语言·网络
云姜.30 分钟前
java多态
java·开发语言·c++
CoderCodingNo40 分钟前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
陳10301 小时前
C++:红黑树
开发语言·c++
大闲在人1 小时前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
一切尽在,你来1 小时前
C++ 零基础教程 - 第 6 讲 常用运算符教程
开发语言·c++