zoukankan      html  css  js  c++  java
  • 二分查找(二)

    相关内容:

    最全的二分查找模板请到:https://blog.csdn.net/qq_19446965/article/details/82184672

    其余练习题1:https://www.cnblogs.com/rnanprince/p/11743414.html
    二分查找(倍增法):https://mp.csdn.net/postedit/102811021
    其余练习题2:https://www.cnblogs.com/rnanprince/p/11761940.html
    ————————————————

    【找到 K 个最接近的元素】

    给定一个排序好的数组,两个整数 k 和 x,从数组中找到最靠近 x(两数之差最小)的 k 个数。返回的结果必须要是按升序排好的。如果有两个数与 x 的差值一样,优先选择数值较小的那个数。

    示例 1:

    输入: [1,2,3,4,5], k=4, x=3
    输出: [1,2,3,4]

    示例 2:

    输入: [1,2,3,4,5], k=4, x=-1
    输出: [1,2,3,4]

    链接:https://leetcode-cn.com/problems/find-k-closest-elements

    class Solution(object):
        def findClosestElements(self, arr, k, x):
            """
            :type arr: List[int]
            :type k: int
            :type x: int
            :rtype: List[int]
            """
            def find_target(arr, target):
                left = 0
                right = len(arr) - 1
                while left + 1 < right:
                    mid = (left + right) // 2
                    if target > arr[mid]:
                        left = mid
                    else:
                        right = mid
                return left
        
            index = find_target(arr, x)
            left, right = index - 1, index
            res = []
            for i in range(k):
                if left < 0:
                    res.append(arr[right])
                    right += 1
                elif right == len(arr):
                    res.append(arr[left])
                    left -= 1
                else:
                    if x - arr[left] <= arr[right] - x: 
                        res.append(arr[left])
                        left -= 1
                    else:
                        res.append(arr[right])
                        right += 1
               
            return sorted(res)

    【寻找旋转排序数组中的最小值】

    假设按照升序排序的数组在预先未知的某个点上进行了旋转。

    ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。请找出其中最小的元素。你可以假设数组中不存在重复元素。

    示例 1:

    输入: [3,4,5,1,2]
    输出: 1


    示例 2:

    输入: [4,5,6,7,0,1,2]

    输出: 0

    链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array

        def findMin(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return -1
                
            left = 0
            right = len(nums) - 1
            target = nums[-1]  # 数组最右端的数字为target
            while left + 1 < right:    		
                mid = (left + right) // 2
                if target > nums[mid]:		
                    right = mid 
                else:
                    left = mid
            
            return min(nums[right], nums[left])
    

    【寻找旋转排序数组中的最小值 II】

    假设按照升序排序的数组在预先未知的某个点上进行了旋转。

    ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。请找出其中最小的元素。注意数组中可能存在重复的元素。

    示例 1:

    输入: [1,3,5]
    输出: 1
    示例 2:

    输入: [2,2,2,0,1]
    输出: 0

    链接:https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii

    class Solution(object):
        def findMin(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return -1
    
            left = 0
            right = len(nums) - 1
            while left + 1< right:
                mid = (left + right) // 2
                if nums[mid] < nums[right]:    # 一定在mid或mid左边
                    right = mid
                elif nums[mid] > nums[right]:  # 一定在mid右边
                    left = mid
                else:
                    right -= 1  # 相等时,一定mid或mid左边
    
            return min(nums[left], nums[right])
    

    【搜索旋转排序数组】

    假设按照升序排序的数组在预先未知的某个点上进行了旋转。

    ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。

    搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。

    你可以假设数组中不存在重复的元素。

    你的算法时间复杂度必须是 O(log n) 级别。

    示例 1:

    输入: nums = [4,5,6,7,0,1,2], target = 0
    输出: 4
    示例 2:

    输入: nums = [4,5,6,7,0,1,2], target = 3
    输出: -1

    链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array

    class Solution(object):
        def search(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: int
            """
            if not nums:
                return -1
            left = 0
            right = len(nums) - 1
            while left + 1 < right:
                mid = (left + right) // 2
                if nums[mid] >= nums[left]:
                    if nums[left] <= target <= nums[mid]:
                        right = mid
                    else:
                        left = mid      # target > nums[mid]
                else:
                    if nums[mid] <= target <= nums[right]:
                        left = mid
                    else:
                        right = mid      # target < nums[mid]
                        
            if nums[left] == target:
                return left
            if nums[right] == target:
                return right
            
            return -1
    

     

    【搜索旋转排序数组 II】

    假设按照升序排序的数组在预先未知的某个点上进行了旋转。

    ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] )。

    编写一个函数来判断给定的目标值是否存在于数组中。若存在返回 true,否则返回 false。

    示例 1:

    输入: nums = [2,5,6,0,0,1,2], target = 0
    输出: true
    示例 2:

    输入: nums = [2,5,6,0,0,1,2], target = 3
    输出: false

    链接:https://leetcode-cn.com/problems/search-in-rotated-sorted-array-ii

    二分法太复杂,不适合

    class Solution(object):
        def search(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: bool
            """
            for num in nums:
                if num == target:
                    return True
            return False
    

    搜索二维矩阵

    编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

    每行中的整数从左到右按升序排列。
    每行的第一个整数大于前一行的最后一个整数。
    示例 1:

    输入:
    matrix = [
    [1, 3, 5, 7],
    [10, 11, 16, 20],
    [23, 30, 34, 50]
    ]
    target = 3
    输出: true

    链接:https://leetcode-cn.com/problems/search-a-2d-matrix

    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            if not matrix or not matrix[0]:
                return False
                
            n, m = len(matrix), len(matrix[0])
            left = 0
            right = n * m - 1
            while left + 1 < right:
                mid = (left + right) // 2
                x, y = mid / m, mid % m   # 还原坐标值
                if matrix[x][y] == target:
                    return True
                elif matrix[x][y] < target:
                    left = mid
                else:
                    right = mid
                    
            x, y = left / m, left % m
            if matrix[x][y] == target:
                return True
            
            x, y = right / m, right % m
            if matrix[x][y] == target:
                return True
            
            return False
    

    【搜索二维矩阵 II】

    编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

    每行的元素从左到右升序排列。
    每列的元素从上到下升序排列。
    示例:

    现有矩阵 matrix 如下:

    [
    [1, 4, 7, 11, 15],
    [2, 5, 8, 12, 19],
    [3, 6, 9, 16, 22],
    [10, 13, 14, 17, 24],
    [18, 21, 23, 26, 30]
    ]
    给定 target = 5,返回 true。

    给定 target = 20,返回 false。

    链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii

    class Solution(object):
        def searchMatrix(self, matrix, target):
            """
            :type matrix: List[List[int]]
            :type target: int
            :rtype: bool
            """
            if not matrix or not matrix[0]:
                return False
            
      
            row, column = len(matrix), len(matrix[0])
            i, j = 0, column -1   # 从右上到左下
    
            while i < row and j >= 0:
                if matrix[i][j] == target:
                    return True
                elif matrix[i][j] < target:
                    i += 1
                elif matrix[i][j] > target:
                    j -= 1
                    
            return False
    
  • 相关阅读:
    ip地址和子网掩码
    Mysql 进阶查询 (select 语句的高级用法)
    MHA高可用配置及故障切换
    数据库的备份与恢复需要修改
    每天一分钟,了解mysql索引,事务与存储引擎
    mysql基础命令详解
    带你走进mysql数据库
    Spring XML无自动提示
    Spring环境搭建错误
    读书笔记_java设计模式深入研究 第十一章 装饰器模式 Decorator
  • 原文地址:https://www.cnblogs.com/rnanprince/p/11761940.html
Copyright © 2011-2022 走看看