[关闭]
@CrazyHenry 2018-01-01T09:49:30.000000Z 字数 1952 阅读 1153

Leetcode33. Search in Rotated Sorted Array

ddddLeetcode刷题


58021-106.jpg-369.5kB

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).
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.

我的代码:时间复杂度O(n)

下标版本:

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-33
  4. //T(n)=O(n), S(n)=O(1)
  5. class Solution {
  6. public:
  7. int search(vector<int>& nums, int target) {
  8. decltype(nums.size()) index = 0;
  9. for(; index < nums.size(); ++index)
  10. {
  11. if(nums[index] == target)
  12. {
  13. return index;
  14. break;
  15. }
  16. }
  17. return -1;
  18. }
  19. };

image.png-55.7kB

迭代器版本:

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-33
  4. //T(n)=O(n), S(n)=O(1)
  5. class Solution {
  6. public:
  7. int search(vector<int>& nums, int target) {
  8. for(auto vbeg = nums.begin(); vbeg != nums.end(); ++vbeg)
  9. {
  10. if(*vbeg == target)
  11. {
  12. return distance(nums.begin(), vbeg);
  13. break;
  14. }
  15. }
  16. return -1;
  17. }
  18. };

image.png-59.3kB

优秀代码:时间复杂度O(logn)

实际上,这个array是有序的,只是有一个旋转,所以,可以采用适当的算法来优化时间复杂度。

  1. //二分查找
  2. class Solution {
  3. public:
  4. int search(const vector<int> &nums, int target)
  5. {
  6. int lo = 0;
  7. int hi = nums.size() - 1;
  8. while (lo <= hi)
  9. {
  10. int mid = (lo + hi) / 2;
  11. if (nums[mid] == target) return mid;
  12. if (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//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. }
  35. return -1;
  36. }
  37. };

image.png-100.8kB

改进一些语言特性:符合标准

image.png-100.8kB

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