C++学习笔记——二分查找及其STL库函数

本文介绍了一种在已排序并旋转的数组中进行二分查找的方法。针对两种情况——无重复数字与有重复数字的数组,分别给出了实现代码。此外还介绍了STL中的二分查找相关函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二分查找学习日记

适用范围:二分查找适用于已经排好序的数组
引自soul machine leetcode 题目:

Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array.

二分查找(无重复数字数组)代码:

// LeetCode, Search in Rotated Sorted Array
//时间复杂度O(log n),空间复杂度O(1)
class Solution {
public:
int search(const vector<int>& nums, int target) {
int first = 0, last = nums.size();
while (first != last) {
const int mid = first + (last - first) / 2;
if (nums[mid] == target)
return mid;
if (nums[first] <= nums[mid]) {
if (nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
} else {
if (nums[mid] < target && target <= nums[last-1])
first = mid + 1;
else
last = mid;
}
}
return -1;
}
};

如果有重复数字:

// LeetCode, Search in Rotated Sorted Array II
// 时间复杂度O(n)空间复杂度 O(1)
class Solution {
public:
bool search(const vector<int>& nums, int target) {
int first = 0, last = nums.size();
while (first != last) {
const int mid = first + (last - first) / 2;
if (nums[mid] == target)
return true;
if (nums[first] < nums[mid]) {
if (nums[first] <= target && target < nums[mid])
last = mid;
else
first = mid + 1;
} else if (nums[first] > nums[mid]) {
if (nums[mid] < target && target <= nums[last-1])
first = mid + 1;
else
last = mid;
} else
//skip duplicate one
first++;
}
return false;
}
};

STL中的二分查找:
头文件#include<algorithm>//sort,upper_bound,lower_bound,binary_search
lower_bound返回一个迭代器指向其中第一个这个元素。
upper_bound返回一个迭代器指向其中最后一个这个元素的下一个位置
binary_search则返回布尔型变量true or false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值