查找排序部分习题 242. 有效的字母异位词 74. 搜索二维矩阵 1. 两数之和 167.两数之和 II

242. 有效的字母异位词

给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

python 复制代码
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        ss = list(s)
        tt = list(t)
        ss.sort()
        tt.sort()
        return ss == tt
python 复制代码
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        return sorted(list(s)) == sorted(list(t))
        # sorted()函数返回重新排序的列表,与sort()函数的区别在于sort()函数是list列表中的函数,而sorted()函数可以对所有可迭代对象进行排序操作。并且用sort()函数对列表排序时会影响列表本身,而sorted()函数则不会。
python 复制代码
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        # 两个字典
        dict1 = {}  # {'a':1 'b':2}
        dict2 = {}
        for ch in s:
            dict1[ch] = dict1.get(ch, 0) + 1
        for ch in t:
            dict2[ch] = dict2.get(ch, 0) + 1
        return dict1 == dict2

74. 搜索二维矩阵

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

线性查找 or 二分查找

python 复制代码
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        for line in matrix:
            if target in line:
                return True
        return False
python 复制代码
class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        h = len(matrix)  # 长度 几行
        if h == 0:
            return False  #[]
        w = len(matrix[0])  # 宽度 几列
        if w == 0:
            return False  # [[], [], []]
        left = 0
        right = w * h - 1
        """
        0 1  2 3
        4 5  6 7
        8 9 10 11
        第9个位置,num//4行,num%4列
        i = num // 4
        j = num % 4
        """
        while left <= right:  #  二分查找代码  候选区有值
            mid = (left + right) // 2
            i = mid // w
            j = mid % w
            if matrix[i][j] == target:
                return True
            elif matrix[i][j] > target:  # 待查找的值在mid左侧
                right = mid - 1
            else:  # matrix[mid] < target  待查找的值在mid右侧
                left = mid + 1
        else:
            return False

1. 两数之和 167.两数之和 II → 输入无序/有序数组

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

python 复制代码
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        n = len(nums)
        for i in range(n):
            for j in range(i):
                if nums[i] + nums[j] == target:
                    return sorted([i,j])

若为有序数组,可二分查找

python 复制代码
class Solution(object):
    def binary_search(self, li, left, right, val):  # 二份查找函数
        # left = 0
        # right = len(li) - 1
        while left <= right:  # 候选区有值
            mid = (left + right) // 2
            if li[mid] == val:
                return mid
            elif li[mid] > val:  # 待查找的值在mid左侧
                right = mid - 1
            else:  # li[mid] < val  待查找的值在mid右侧
                left = mid + 1
        else:
            return None
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """

        for i in range(len(nums)):
            a = nums[i]
            b = target - a
            if b >= a:
                j = self.binary_search(nums, i + 1, len(nums) - 1, b)
            else:
                j = self.binary_search(nums, 0, i - 1, b)
            if j:
                break
        return sorted([i+1, j+1])  # 题目需要输出index

无序列表的二分查找

python 复制代码
class Solution(object):
    def binary_search(self, li, left, right, val):  # 二份查找函数
        # left = 0
        # right = len(li) - 1
        while left <= right:  # 候选区有值
            mid = (left + right) // 2
            if li[mid][0] == val:
                return mid
            elif li[mid][0] > val:  # 待查找的值在mid左侧
                right = mid - 1
            else:  # li[mid] < val  待查找的值在mid右侧
                left = mid + 1
        else:
            return None
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        new_nums = [[num, i] for i, num in enumerate(nums)]  # 二维列表 每一行有 数字num 下标i
        new_nums.sort(key = lambda x:x[0]) # 按照数num排序  new_nums[i][0]是数,new_nums[i][1]是原来的下标

        for i in range(len(new_nums)):
            a = new_nums[i][0]
            b = target - a
            if b >= a:
                j = self.binary_search(new_nums, i + 1, len(new_nums) - 1, b)
            else:
                j = self.binary_search(new_nums, 0, i - 1, b)
            if j:
                break
        return sorted([new_nums[i][1], new_nums[j][1]])
相关推荐
dev派21 分钟前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪2 小时前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663672 小时前
将 PDF 文档转换为图片【Python 教程】
python
CoovallyAIHub3 小时前
9个视觉语言模型工厂实测:Qwen 87.9%碾压全场,你的显卡能跑哪个?
算法
悟空爬虫4 小时前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
SparkX开源AI知识库4 小时前
手摸手带你安装OpenClaw并对接飞书
算法·架构
dev派4 小时前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain
一语07164 小时前
3分钟搞懂深度学习AI:实操篇:卷积层
人工智能·算法
明月_清风6 小时前
从“能用”到“专业”:构建生产级装饰器与三层逻辑拆解
后端·python
曲幽15 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic