classSolution { public: intguessNumber(int n){ long l = 0, r = n, mid; while (l < r) { mid = l + r >> 1; if (guess(mid) <= 0) r = mid; else l = mid + 1; } return l; } };
classSolution { public: intfirstBadVersion(int n){ long l = 0, r = n, mid; while (l < r) { mid = l + r >> 1; if (isBadVersion(mid)) r = mid; else l = mid + 1; } return l; } };
classSolution { public: intfindMin(vector<int>& nums){ int l = 0, r = nums.size() - 1, mid; while (l < r) { mid = l + r >> 1; if (nums[mid] <= nums[r]) r = mid; else l = mid + 1; } return nums[l]; } };
classSolution { public: intsearch(vector<int>& nums, int target){ int n = nums.size(), l = 0, r = n - 1, mid; /* 找到旋转排序数组中的最小值(模板一) */ while (l < r) { mid = l + r >> 1; if (nums[mid] <= nums[r]) r = mid; else l = mid + 1; } /* 根据情况重新分配区域 */ if (target <= nums[n - 1]) r = n - 1; else r = l - 1, l = 0; /* 搜索排序数组(模板一) */ while (l < r) { mid = l + r >> 1; if (nums[mid] >= target) r = mid; else l = mid + 1; } return nums[l] == target ? l : -1; } };
classSolution { public: boolisPerfectSquare(int num){ long l = 1, r = num, mid; while (l < r) { mid = l + r >> 1; if (mid >= num / mid) r = mid; else l = mid + 1; } return (l * l == num) ? true : false; } };
classSolution { public: vector<int> twoSum(vector<int>& numbers, int target){ int l = 0, r = numbers.size() - 1, mid; int start, end; for (int i = 0; i < numbers.size() - 1; i++) { start = i, l = i + 1, r = numbers.size() - 1; while (l < r) { mid = l + r >> 1; if (numbers[mid] >= (target - numbers[i])) r = mid; else l = mid + 1; } end = l; if (numbers[end] == (target - numbers[start])) { break; } } return {start + 1, end + 1}; } };