C++學習筆記——二分查找及其STL庫函數

二分查找學習日記

適用範圍:二分查找適用於已經排好序的數組
引自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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章