[Binary Search] Leetcode 35, 74

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

[Binary Search] Leetcode 35, 74的相关文章

(双指针、二分Binary Search) leetcode 658. Find K closest Elements

题意:给定一个升序排列的数组,找到k个与x最相近的元素(即差值最小),返回的结果必须要是按升序排好的.如果有两个数与 x的差值一样,优先选择数值较小的那个数. 解法一:双指针(排除法),一个一个删,因为是有序数组,且返回的是连续升序子数组,所以每一次删除的元素一定是位于边界:如果数组含有共 7 个元素,要保留 3 个元素,因此要删除 4 个元素(arr.size()-k):因为要删除的元素都位于边界,于是可以使用双指针(左指针指向数组的第一个元素,右指针指向数组最后一个元素)对撞的方式确定保留区

LeetCode 501. Find Mode in Binary Search Tree (找到二叉搜索树的众数)

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to the nod

[LeetCode][JavaScript]Lowest Common Ancestor of a Binary Search Tree

Lowest Common Ancestor of a Binary Search Tree Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two

LeetCode 5题 --Array+Binary search

这5道题都是array的binary search就可以搞定了 分别是leetcode(35)--Search Insert Position  leetcode(33)--Search in Rotated Sorted Array  leetcode(81)--Search in Rotated Sorted Array II  leetcode(34)--Search for a Range  leetcode(74)--Search a 2D Matrix 一:leetcode(35)-

LeetCode: Validata Binary Search Tree

LeetCode: Validata Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree o

[LeetCode][JavaScript]Unique Binary Search Trees II

Unique Binary Search Trees II Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example,Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1

Leetcode Binary Search Conclusion

278 First Bad Version23.7%Easy 278. First Bad Version 349 Intersection of Two Arrays44.5%Easy 374 Guess Number Higher or Lower32.2%Easy 350 Intersection of Two Arrays II42.6%Easy 270 Closest Binary Search Tree Value 36.3%Easy 50 Pow(x, n)27.4%Medium

Recover Binary Search Tree leetcode java

题目: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 题解: 解决方法是利用中序遍历找顺序不对的两个点

【leetcode刷题笔记】Recover Binary Search Tree

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 题解:需要找到二叉搜索树中乱序的两个节点,并把它们交换回来