LeetCode81 Search in Rotated Sorted Array II
题目:
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array. (Medium)
分析:
这个题目的意义在于分析出时间复杂度和找出最差的情况。
在Search in Rotated Sorted Array I中利用的target和num[0]的关系进行二分。
但是当存在重复元素的时候,如果遇到相等情况则无法二分,只能向前一步;
极端情况下,诸如数组[1,1,1,0,1,1...1,1,1]的情况,算法的复杂度退化到了O(n);
直接写一个遍历的代码:
1 class Solution { 2 public: 3 bool search(vector<int>& nums, int target) { 4 for (int i = 0; i < nums.size(); ++i) { 5 if (nums[i] == target) { 6 return true; 7 } 8 } 9 return false; 10 } 11 };