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.1%
0033Search in Rotated Sorted ArrayGoMedium36.5%
0034Find First and Last Position of Element in Sorted ArrayGoMedium38.2%
0035Search Insert PositionGoEasy42.8%
0069Sqrt(x)GoEasyO(log n)O(1)35.8%
0074Search a 2D MatrixGoMedium39.1%
0081Search in Rotated Sorted Array IIGoMedium33.9%
0153Find Minimum in Rotated Sorted ArrayGoMedium46.7%
0154Find Minimum in Rotated Sorted Array IIGoHard42.3%
0162Find Peak ElementGoMedium44.3%
0167Two Sum II - Input array is sortedGoEasyO(n)O(1)56.3%
0209Minimum Size Subarray SumGoMediumO(n)O(1)40.5%
0222Count Complete Tree NodesGoMediumO(n)O(1)50.9%
0240Search a 2D Matrix IIGoMedium46.0%
0275H-Index IIGoMedium36.5%
0278First Bad VersionGoEasy38.5%
0287Find the Duplicate NumberGoMediumO(n)O(1)❤️58.1%
0300Longest Increasing SubsequenceGoMediumO(n log n)O(n)46.0%
0315Count of Smaller Numbers After SelfGoHard42.0%
0327Count of Range SumGoHard36.2%
0349Intersection of Two ArraysGoEasyO(n)O(n)66.3%
0350Intersection of Two Arrays IIGoEasyO(n)O(n)52.6%
0354Russian Doll EnvelopesGoHard38.4%
0367Valid Perfect SquareGoEasy42.4%
0374Guess Number Higher or LowerGoEasy45.8%
0378Kth Smallest Element in a Sorted MatrixGoMedium57.8%
0410Split Array Largest SumGoHard47.4%
0436Find Right IntervalGoMedium48.8%
0441Arranging CoinsGoEasy42.9%
0456132 PatternGoMedium30.7%
0475HeatersGoMedium34.0%
0483Smallest Good BaseGoHard36.7%
0493Reverse PairsGoHard27.9%
0497Random Point in Non-overlapping RectanglesGoMedium39.1%
0528Random Pick with WeightGoMedium45.1%
0532K-diff Pairs in an ArrayGoMedium36.1%
0633Sum of Square NumbersGoMedium32.9%
0658Find K Closest ElementsGoMedium43.4%
0668Kth Smallest Number in Multiplication TableGoHard48.4%
0704Binary SearchGoEasy54.8%
0710Random Pick with BlacklistGoHardO(n)O(n)33.2%
0718Maximum Length of Repeated SubarrayGoMedium51.2%
0719Find K-th Smallest Pair DistanceGoHard33.0%
0744Find Smallest Letter Greater Than TargetGoEasy45.7%
0778Swim in Rising WaterGoHard57.7%
0786K-th Smallest Prime FractionGoHard45.1%
0793Preimage Size of Factorial Zeroes FunctionGoHard40.6%
0826Most Profit Assigning WorkGoMedium39.6%
0852Peak Index in a Mountain ArrayGoEasy71.6%
0862Shortest Subarray with Sum at Least KGoHard25.3%
0875Koko Eating BananasGoMedium53.8%
0878Nth Magical NumberGoHard29.1%
0887Super Egg DropGoHard26.9%
0888Fair Candy SwapGoEasy59.4%
0911Online ElectionGoMedium51.8%
0981Time Based Key-Value StoreGoMedium54.3%
1004Max Consecutive Ones IIIGoMedium60.8%
1011Capacity To Ship Packages Within D DaysGoMedium60.7%
1157Online Majority Element In SubarrayGoHard41.4%
1170Compare Strings by Frequency of the Smallest CharacterGoMedium60.6%
1201Ugly Number IIIGoMedium26.8%
1208Get Equal Substrings Within BudgetGoMedium44.9%
1235Maximum Profit in Job SchedulingGoHard48.2%
1283Find the Smallest Divisor Given a ThresholdGoMedium50.8%
1300Sum of Mutated Array Closest to TargetGoMedium42.6%
1337The K Weakest Rows in a MatrixGoEasy71.9%
1385Find the Distance Value Between Two ArraysGoEasy66.5%
1439Find the Kth Smallest Sum of a Matrix With Sorted RowsGoHard61.2%
1482Minimum Number of Days to Make m BouquetsGoMedium52.4%
1539Kth Missing Positive NumberGoEasy54.7%
1608Special Array With X Elements Greater Than or Equal XGoEasy61.5%
1631Path With Minimum EffortGoMedium50.3%
1648Sell Diminishing-Valued Colored BallsGoMedium31.4%
1649Create Sorted Array through InstructionsGoHard36.9%
1658Minimum Operations to Reduce X to ZeroGoMedium33.3%
——————————————————————-——-—————-—————————-————-————-

⬅️上一页

下一页➡️

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