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 ArraysGoHard32.8%
0033Search in Rotated Sorted ArrayGoMedium36.9%
0034Find First and Last Position of Element in Sorted ArrayGoMedium38.8%
0035Search Insert PositionGoEasy42.6%
0069Sqrt(x)GoEasyO(log n)O(1)36.0%
0074Search a 2D MatrixGoMedium40.4%
0081Search in Rotated Sorted Array IIGoMedium34.1%
0153Find Minimum in Rotated Sorted ArrayGoMedium47.3%
0154Find Minimum in Rotated Sorted Array IIGoHard42.4%
0162Find Peak ElementGoMedium44.9%
0167Two Sum II - Input array is sortedGoEasyO(n)O(1)57.1%
0209Minimum Size Subarray SumGoMediumO(n)O(1)41.3%
0222Count Complete Tree NodesGoMediumO(n)O(1)52.0%
0240Search a 2D Matrix IIGoMedium46.7%
0275H-Index IIGoMedium36.7%
0278First Bad VersionGoEasy39.6%
0287Find the Duplicate NumberGoMediumO(n)O(1)❤️58.2%
0300Longest Increasing SubsequenceGoMediumO(n log n)O(n)47.1%
0315Count of Smaller Numbers After SelfGoHard42.0%
0327Count of Range SumGoHard36.1%
0349Intersection of Two ArraysGoEasyO(n)O(n)67.2%
0350Intersection of Two Arrays IIGoEasyO(n)O(n)53.7%
0354Russian Doll EnvelopesGoHard39.1%
0367Valid Perfect SquareGoEasy42.6%
0374Guess Number Higher or LowerGoEasy46.6%
0378Kth Smallest Element in a Sorted MatrixGoMedium58.4%
0410Split Array Largest SumGoHard48.4%
0436Find Right IntervalGoMedium48.9%
0441Arranging CoinsGoEasy43.2%
0456132 PatternGoMedium30.7%
0475HeatersGoMedium34.4%
0483Smallest Good BaseGoHard37.1%
0493Reverse PairsGoHard28.7%
0497Random Point in Non-overlapping RectanglesGoMedium39.1%
0528Random Pick with WeightGoMedium45.5%
0532K-diff Pairs in an ArrayGoMedium36.8%
0611Valid Triangle NumberGoMedium49.1%
0633Sum of Square NumbersGoMedium34.6%
0658Find K Closest ElementsGoMedium43.6%
0668Kth Smallest Number in Multiplication TableGoHard48.7%
0704Binary SearchGoEasy55.0%
0710Random Pick with BlacklistGoHardO(n)O(n)33.2%
0718Maximum Length of Repeated SubarrayGoMedium51.2%
0719Find K-th Smallest Pair DistanceGoHard33.5%
0744Find Smallest Letter Greater Than TargetGoEasy45.9%
0778Swim in Rising WaterGoHard57.9%
0786K-th Smallest Prime FractionGoHard46.6%
0793Preimage Size of Factorial Zeroes FunctionGoHard41.0%
0826Most Profit Assigning WorkGoMedium40.2%
0852Peak Index in a Mountain ArrayGoEasy71.4%
0862Shortest Subarray with Sum at Least KGoHard25.8%
0875Koko Eating BananasGoMedium54.0%
0878Nth Magical NumberGoHard29.4%
0887Super Egg DropGoHard26.9%
0888Fair Candy SwapGoEasy59.8%
0911Online ElectionGoMedium51.8%
0981Time Based Key-Value StoreGoMedium53.5%
1004Max Consecutive Ones IIIGoMedium61.5%
1011Capacity To Ship Packages Within D DaysGoMedium61.5%
1157Online Majority Element In SubarrayGoHard41.7%
1170Compare Strings by Frequency of the Smallest CharacterGoMedium60.8%
1201Ugly Number IIIGoMedium27.2%
1208Get Equal Substrings Within BudgetGoMedium45.3%
1235Maximum Profit in Job SchedulingGoHard50.2%
1283Find the Smallest Divisor Given a ThresholdGoMedium51.8%
1300Sum of Mutated Array Closest to TargetGoMedium42.4%
1337The K Weakest Rows in a MatrixGoEasy72.1%
1385Find the Distance Value Between Two ArraysGoEasy66.4%
1439Find the Kth Smallest Sum of a Matrix With Sorted RowsGoHard61.3%
1482Minimum Number of Days to Make m BouquetsGoMedium53.6%
1539Kth Missing Positive NumberGoEasy54.8%
1608Special Array With X Elements Greater Than or Equal XGoEasy60.9%
1631Path With Minimum EffortGoMedium50.8%
1648Sell Diminishing-Valued Colored BallsGoMedium31.3%
1649Create Sorted Array through InstructionsGoHard37.0%
1658Minimum Operations to Reduce X to ZeroGoMedium33.4%
1818Minimum Absolute Sum DifferenceGoMedium28.2%
——————————————————————-——-—————-—————————-————-————-

⬅️上一页

下一页➡️

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