2.11 Binary Search

Binary Search #

  • 二分搜索的经典写法。需要注意的三点:
    1. 循环退出条件,注意是 low <= high,而不是 low < high。
    2. mid 的取值,mid := low + (high-low)»1
    3. low 和 high 的更新。low = mid + 1,high = mid - 1。
func binarySearchMatrix(nums []int, target int) int {
	low, high := 0, len(nums)-1
	for low <= high {
		mid := low + (high-low)>>1
		if nums[mid] == target {
			return mid
		} else if nums[mid] > target {
			high = mid - 1
		} else {
			low = mid + 1
		}
	}
	return -1
}
  • 二分搜索的变种写法。有 4 个基本变种:
    1. 查找第一个与 target 相等的元素,时间复杂度 O(logn)
    2. 查找最后一个与 target 相等的元素,时间复杂度 O(logn)
    3. 查找第一个大于等于 target 的元素,时间复杂度 O(logn)
    4. 查找最后一个小于等于 target 的元素,时间复杂度 O(logn)
// 二分查找第一个与 target 相等的元素,时间复杂度 O(logn)
func searchFirstEqualElement(nums []int, target int) int {
	low, high := 0, len(nums)-1
	for low <= high {
		mid := low + ((high - low) >> 1)
		if nums[mid] > target {
			high = mid - 1
		} else if nums[mid] < target {
			low = mid + 1
		} else {
			if (mid == 0) || (nums[mid-1] != target) { // 找到第一个与 target 相等的元素
				return mid
			}
			high = mid - 1
		}
	}
	return -1
}

// 二分查找最后一个与 target 相等的元素,时间复杂度 O(logn)
func searchLastEqualElement(nums []int, target int) int {
	low, high := 0, len(nums)-1
	for low <= high {
		mid := low + ((high - low) >> 1)
		if nums[mid] > target {
			high = mid - 1
		} else if nums[mid] < target {
			low = mid + 1
		} else {
			if (mid == len(nums)-1) || (nums[mid+1] != target) { // 找到最后一个与 target 相等的元素
				return mid
			}
			low = mid + 1
		}
	}
	return -1
}

// 二分查找第一个大于等于 target 的元素,时间复杂度 O(logn)
func searchFirstGreaterElement(nums []int, target int) int {
	low, high := 0, len(nums)-1
	for low <= high {
		mid := low + ((high - low) >> 1)
		if nums[mid] >= target {
			if (mid == 0) || (nums[mid-1] < target) { // 找到第一个大于等于 target 的元素
				return mid
			}
			high = mid - 1
		} else {
			low = mid + 1
		}
	}
	return -1
}

// 二分查找最后一个小于等于 target 的元素,时间复杂度 O(logn)
func searchLastLessElement(nums []int, target int) int {
	low, high := 0, len(nums)-1
	for low <= high {
		mid := low + ((high - low) >> 1)
		if nums[mid] <= target {
			if (mid == len(nums)-1) || (nums[mid+1] > target) { // 找到最后一个小于等于 target 的元素
				return mid
			}
			low = mid + 1
		} else {
			high = mid - 1
		}
	}
	return -1
}
  • 在基本有序的数组中用二分搜索。经典解法可以解,变种写法也可以写,常见的题型,在山峰数组中找山峰,在旋转有序数组中找分界点。第 33 题,第 81 题,第 153 题,第 154 题,第 162 题,第 852 题
func peakIndexInMountainArray(A []int) int {
	low, high := 0, len(A)-1
	for low < high {
		mid := low + (high-low)>>1
		// 如果 mid 较大,则左侧存在峰值,high = m,如果 mid + 1 较大,则右侧存在峰值,low = mid + 1
		if A[mid] > A[mid+1] {
			high = mid
		} else {
			low = mid + 1
		}
	}
	return low
}
  • max-min 最大值最小化问题。求在最小满足条件的情况下的最大值。第 410 题,第 875 题,第 1011 题,第 1283 题。
No.TitleSolutionDifficultyTimeComplexitySpaceComplexityFavoriteAcceptance
0004Median of Two Sorted ArraysGoHard31.4%
0029Divide Two IntegersGoMedium16.9%
0033Search in Rotated Sorted ArrayGoMedium36.1%
0034Find First and Last Position of Element in Sorted ArrayGoMedium37.5%
0035Search Insert PositionGoEasy42.9%
0050Pow(x, n)GoMediumO(log n)O(1)31.1%
0069Sqrt(x)GoEasyO(log n)O(1)35.4%
0074Search a 2D MatrixGoMedium38.1%
0081Search in Rotated Sorted Array IIGoMedium33.7%
0153Find Minimum in Rotated Sorted ArrayGoMedium46.4%
0154Find Minimum in Rotated Sorted Array IIGoHard42.1%
0162Find Peak ElementGoMedium44.1%
0167Two Sum II - Input array is sortedGoEasyO(n)O(1)55.8%
0174Dungeon GameGoHard33.4%
0209Minimum Size Subarray SumGoMediumO(n)O(1)39.8%
0222Count Complete Tree NodesGoMediumO(n)O(1)49.8%
0230Kth Smallest Element in a BSTGoMediumO(n)O(1)63.0%
0240Search a 2D Matrix IIGoMedium45.4%
0275H-Index IIGoMedium36.4%
0287Find the Duplicate NumberGoMediumO(n)O(1)❤️57.9%
0300Longest Increasing SubsequenceGoMediumO(n log n)O(n)44.5%
0315Count of Smaller Numbers After SelfGoHard42.4%
0327Count of Range SumGoHard36.3%
0349Intersection of Two ArraysGoEasyO(n)O(n)65.3%
0350Intersection of Two Arrays IIGoEasyO(n)O(n)52.2%
0354Russian Doll EnvelopesGoHard37.7%
0367Valid Perfect SquareGoEasy42.2%
0378Kth Smallest Element in a Sorted MatrixGoMedium56.5%
0392Is SubsequenceGoEasyO(n)O(1)49.6%
0410Split Array Largest SumGoHard46.7%
0436Find Right IntervalGoMedium48.6%
0441Arranging CoinsGoEasy42.6%
04544Sum IIGoMediumO(n^2)O(n)54.7%
0475HeatersGoMedium33.7%
0483Smallest Good BaseGoHard36.3%
0493Reverse PairsGoHard27.2%
0497Random Point in Non-overlapping RectanglesGoMedium39.1%
0528Random Pick with WeightGoMedium44.8%
0658Find K Closest ElementsGoMedium42.3%
0668Kth Smallest Number in Multiplication TableGoHard47.9%
0704Binary SearchGoEasy54.4%
0710Random Pick with BlacklistGoHardO(n)O(n)33.1%
0718Maximum Length of Repeated SubarrayGoMedium50.5%
0719Find K-th Smallest Pair DistanceGoHard32.7%
0744Find Smallest Letter Greater Than TargetGoEasy45.6%
0778Swim in Rising WaterGoHard55.0%
0786K-th Smallest Prime FractionGoHard43.4%
0793Preimage Size of Factorial Zeroes FunctionGoHard40.7%
0852Peak Index in a Mountain ArrayGoEasy71.8%
0862Shortest Subarray with Sum at Least KGoHard25.3%
0875Koko Eating BananasGoMedium53.5%
0878Nth Magical NumberGoHard28.9%
0887Super Egg DropGoHard27.0%
0911Online ElectionGoMedium51.4%
0927Three Equal PartsGoHard34.6%
0981Time Based Key-Value StoreGoMedium54.2%
1011Capacity To Ship Packages Within D DaysGoMedium59.9%
1111Maximum Nesting Depth of Two Valid Parentheses StringsGoMedium72.7%
1157Online Majority Element In SubarrayGoHard40.9%
1170Compare Strings by Frequency of the Smallest CharacterGoMedium60.4%
1201Ugly Number IIIGoMedium26.5%
1235Maximum Profit in Job SchedulingGoHard47.7%
1283Find the Smallest Divisor Given a ThresholdGoMedium49.9%
1300Sum of Mutated Array Closest to TargetGoMedium43.0%
1337The K Weakest Rows in a MatrixGoEasy72.1%
1631Path With Minimum EffortGoMedium49.9%
1649Create Sorted Array through InstructionsGoHard36.6%
1658Minimum Operations to Reduce X to ZeroGoMedium33.3%
——————————————————————-——-—————-—————————-————-————-

⬅️上一页

下一页➡️

Calendar Apr 13, 2021
Edit Edit this page
本站总访问量:  次 您是本站第  位访问者