-
求开方: https://leetcode-cn.com/problems/sqrtx/
class Solution { public: int mySqrt(int x) { int l = 0, r = x, ans = -1; while (l <= r) { int mid = l + (r - l) / 2; if ((long long)mid * mid <= x) // long long的最大值:9223372036854775807(>10^18) { // long long的最小值:-9223372036854775808 ans = mid; l = mid + 1; } else { r = mid - 1; } } return ans; } };
-
有序数组中的单一元素: https://leetcode-cn.com/problems/single-element-in-a-sorted-array/
class Solution { public: int singleNonDuplicate(vector<int>& nums) { int lo = 0; int hi = nums.size() - 1; while (lo < hi) { int mid = lo + (hi - lo) / 2; bool halvesAreEven = (hi - mid) % 2 == 0; if (nums[mid + 1] == nums[mid]) { if (halvesAreEven) { lo = mid + 2; } else { hi = mid - 1; } } else if (nums[mid - 1] == nums[mid]) { if (halvesAreEven) { hi = mid - 2; } else { lo = mid + 1; } } else { return nums[mid]; } } return nums[lo]; } }; // 另外,你会发现即使数组没有经过排序,只要将同一元素放在一起,该算法仍然起作用 //(例:[10, 10, 4, 4, 7, 11, 11, 12, 12, 2, 2])。他们的顺序无关紧要,重要的是含有单个元素的子数组元素个数为奇数。
-
寻找旋转排序数组中的最小值: https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/
class Solution { public: int findMin(vector<int>& nums) { int low = 0; int high = nums.size() - 1; while (low < high) { int pivot = low + (high - low) / 2; if (nums[pivot] < nums[high]) { high = pivot; } else { low = pivot + 1; } } return nums[low]; } };
【数据结构c++】二分查找(十一)
最新推荐文章于 2024-11-13 17:29:28 发布