35. Search Insert Position
Description
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5 Output: 2
Example 2:
Input: [1,3,5,6], 2 Output: 1
Example 3:
Input: [1,3,5,6], 7 Output: 4
Example 4:
Input: [1,3,5,6], 0 Output: 0
Solution
二分法查找
1 class Solution: 2 def searchInsert(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: int 7 """ 8 l, r = 0, len(nums) 9 10 while l < r: 11 m = (l + r) // 2 12 if nums[m] == target: 13 return m 14 elif nums[m] > target: 15 r = m 16 else: 17 l = m + 1 18 return l
74. Search a 2D Matrix
Description
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 3 Output: true
Example 2:
Input: matrix = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ] target = 13 Output: false
Solution
Approach 1: 二分查找
先按行二分确定目标所在行;再在该行中确定元素位置。
1 class Solution: 2 def searchMatrix(self, matrix, target): 3 """ 4 :type matrix: List[List[int]] 5 :type target: int 6 :rtype: bool 7 """ 8 if not matrix or not matrix[0]: return False 9 m, n = len(matrix), len(matrix[0]) 10 11 if target < matrix[0][0] or target > matrix[m - 1][n - 1]: 12 return False 13 14 start, end = 0, m 15 while start < end: 16 midrow = (start + end) // 2 17 if matrix[midrow][0] == target: 18 return True 19 elif target < matrix[midrow][0]: 20 end = midrow 21 else: start = midrow + 1 22 row = start - 1 23 24 l, r = 0, n 25 26 while l < r: 27 midcol = (l + r) // 2 28 if matrix[row][midcol] == target: return True 29 elif matrix[row][midcol] < target: 30 l = midcol + 1 31 else: r = midcol 32 return False
Beats: 41.43%
Runtime: 48ms
Approach 2: 从右上到左下查找
若当前 > target, 则向前一列查找 => 则矩阵后几列均不用再考虑;
若当前 < target, 则向下一行查找 => 则矩阵前几行均不用再考虑。
1 class Solution: 2 def searchMatrix(self, matrix, target): 3 """ 4 :type matrix: List[List[int]] 5 :type target: int 6 :rtype: bool 7 """ 8 if not matrix or not matrix[0]: return False 9 10 rows, cols = len(matrix), len(matrix[0]) 11 row, col = 0, cols - 1 12 while True: 13 if row < rows and col >= 0: 14 if matrix[row][col] == target: 15 return True 16 elif matrix[row][col] < target: 17 row += 1 18 else: col -= 1 19 else: return False
Beats: 41.67%
Runtime: 48ms
原文地址:https://www.cnblogs.com/shiyublog/p/9667820.html
时间: 2024-10-06 04:16:54