二分查找法
要求给定数据是有序的:
int BinarySearch1(vector<int> num, int n) { int left = 0, right = num.size() - 1; int mid ; while (left<= right) { mid = left + (right - left) / 2; if (num[mid] > n) right = mid - 1; else if (num[mid] < n) left = mid + 1; else return mid; } return -1; }
时间复杂度O(logn)