binary search【leetcode34,35,74,240】

一、模板

题目:

A = [1,2,3,3,4]
target = 3
<<

#key points:
#start + 2 < end
#start + (end - start)/2
#A[mid] ==.<.>
#A[start] A[end] ? target
#适用范围:可以转换为first/last position of 的题目

start = 0
end = len(A)-1
while(start+1 target
        end = mid
if A[start] == target: #若找last position,两个if换一下
    return start
if A[end] == target:
    return end
return -1

二、【leetcode34】search for a range

Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4]

class Solution(object):
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        start = 0 
        end = len(nums)-1
        result = [-1,-1]
        if nums == []: #注意特殊情况
            return result
        while (start+1 < end):
	        mid = start + (end-start)/2
	        if nums[mid] == target:
		        end = mid
	        elif nums[mid] < target:
		        start = mid
	        elif nums[mid] > target:
		        end = mid

        if nums[start] == target:
	        result[0] = start
        elif nums[end] == target:
	        result[0] = end
        else:
	        return result

        start = 0 
        end = len(nums)-1
        while (start+1 < end):
	        mid = start + (end-start)/2
	        if nums[mid] == target:
		        start = mid
	        elif nums[mid] < target:
		        start = mid
	        elif nums[mid] > target:
		        end = mid

        if nums[end] == target:
	        result[1] = end
        elif nums[start] == target:
	        result[1] = start
        else:
	        return result
        return result

模板应用:分别寻找 first position和last position,用两次模板


三、【leetcode35】search insert position

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.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

class Solution(object):
    def searchInsert(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        if nums == []:
            return 0
        start = 0 
        end = len(nums)-1
        while start + 1 < end:
	        mid = start + (end - start)/2
	        if nums[mid] >= target:
		        end = mid
	        elif nums[mid] < target:
		        start = mid

        if nums[start] >= target:
	        return start
        elif nums[end] >= target:
	        return end
        else:
	        return len(nums) #注意考虑边界
模板应用:寻找第一个>=target的数的位置,请注意target>max(nums)的情况


四、【leetcode74】search A 2D Matrix

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.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix == []:
            return False
        if matrix == [[]]:
            return False
        m,n = len(matrix), len(matrix[0])
        start = 0
        end = m*n-1
        while start + 1 < end:
            mid = start + (end - start)/2
            x,y = mid/n, mid%n #注意是m还是n
            if matrix[x][y] < target:
                start = mid
            else:
                end = mid

        x,y = start/n, start%n
        if matrix[x][y] == target:
            return True

        x,y = end/n, end%n
        if matrix[x][y] == target:
            return True

        return False
模板应用:

如果用for将matrix遍历,再对每个matrix[i]进行二分法查找,时间复杂度为O(n2);

如果在确定哪一行时使用找到matrix[i][0]或matrix[i][-1],会有边界问题,较为复杂;

方法应为end = m*n -1,用x=mid/n.y=mid%n,确定元素位置的方法使用二分法。


五、【leetcode240】search  a 2D maxtrix 2

1、

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following 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]
]

Given target = 5, return true.

Given target = 20, return false.

2、思路

从左下角查起,如果matrix[x][y] < target,删去第x列,反之,删去第y行,如果相等,return true。这样的时间复杂度为m+n

3、

class Solution(object):
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if matrix == []:
            return False
        if matrix == [[]]:
            return False
        m,n = len(matrix)-1,0
        while n < len(matrix[0]) and m >= 0:
            if matrix[m][n] < target:
                n += 1 
            elif matrix[m][n] > target:
                m -= 1
            elif matrix[m][n] == target:
                return True
        return False


你可能感兴趣的:(leetcode)