[关闭]
@CrazyHenry 2018-01-01T09:48:47.000000Z 字数 1690 阅读 1113

Leetcode81. Search in Rotated Sorted Array II

ddddLeetcode刷题


62171-106.jpg-396kB


Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Suppose an array sorted in ascending order 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).
Write a function to determine if a given target is in the array.
The array may contain duplicates.

考虑这样的例子:[1,3,1,1,1],如果使用昨天的代码:
IMG_20171207_161214.jpg-2402.6kB

我的代码:按照昨天的代码修改一下

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-81
  4. //T(n)=O(logn), S(n)=O(1)
  5. class Solution {
  6. public:
  7. int search(const vector<int> &nums, int target)
  8. {
  9. int lo = 0;
  10. int hi = nums.size() - 1;
  11. while (lo <= hi)
  12. {
  13. int mid = (lo + hi) / 2;
  14. if (nums[mid] == target) return true;
  15. if (nums[lo] < nums[mid]) //把这里改成nums[lo] < nums[mid],[lo,mid]一定有序
  16. {
  17. if (target >= nums[lo] && target < nums[mid])
  18. {
  19. hi = mid - 1;
  20. }
  21. else
  22. {
  23. lo = mid + 1;
  24. }
  25. }
  26. else if (nums[lo] > nums[mid]) //[lo,mid]一定无序,[mid,hi]一定有序
  27. {
  28. if (target > nums[mid] && target <= nums[hi])
  29. {
  30. lo = mid + 1;
  31. }
  32. else
  33. {
  34. hi = mid - 1;
  35. }
  36. }
  37. else //nums[lo] == nums[mid]
  38. {
  39. ++lo;//跳过与nums[mid]重复的nums[lo]
  40. }
  41. }
  42. return false;
  43. }
  44. };

image.png-84.1kB

修改使其符合标准

  1. class Solution {
  2. public:
  3. int search(const vector<int> &nums, int target)
  4. {
  5. if(nums.empty()) return false;
  6. decltype(nums.size()) lo = 0;
  7. auto hi = nums.size() - 1;
  8. while (lo <= hi)
  9. {
  10. auto mid = (lo + hi) / 2;
  11. if (nums[mid] == target) return true;
  12. if (nums[lo] < nums[mid]) //把这里改成nums[lo] < nums[mid],[lo,mid]一定有序
  13. {
  14. if (target >= nums[lo] && target < nums[mid])
  15. {
  16. hi = mid - 1;
  17. }
  18. else
  19. {
  20. lo = mid + 1;
  21. }
  22. }
  23. else if (nums[lo] > nums[mid]) //[lo,mid]一定无序,[mid,hi]一定有序
  24. {
  25. if (target > nums[mid] && target <= nums[hi])
  26. {
  27. lo = mid + 1;
  28. }
  29. else
  30. {
  31. hi = mid - 1;
  32. }
  33. }
  34. else //nums[lo] == nums[mid]
  35. {
  36. ++lo;//跳过与nums[mid]重复的nums[lo]
  37. }
  38. }
  39. return false;
  40. }
  41. };

image.png-90.8kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注