Bayi. Search in rotated Sorted Array II

Source: Internet
Author: User

Follow to "Search in rotated Sorted Array":
What if duplicates is allowed?

Would this affect the run-time complexity? How and why?

Write a function to determine if a given the target was in the array.

This topic is in https://leetcode.com/problems/search-in-rotated-sorted-array/
On the basis of the addition of the Allow to have the same element for this condition.
Then there will be a special case, such as 1,1,1,1,1,3,3 after rotation for 1,3,3,1,1,1,1.
When the middle element equals the first element, put l++, because target! =nums[mid].
and Nums[mid]=nums[l], can be launched target! =NUMS[L].

classSolution { Public:BOOLSearch vector<int>& Nums,intTarget) {intL=0, R=nums.size ()-1; while(L&LT;=R) {intMid= (L+R)/2;if(Nums[mid]==target)return true;Else if(Nums[mid]>nums[l]) {//increments the sequence on the left                if(Target>=nums[l]&&target<nums[mid]) r=mid-1;ElseL=mid+1; }Else if(Nums[mid]<nums[l]) {if(Target>nums[mid]&&target<=nums[r]) l=mid+1;Elser=mid-1; }Else if(Nums[mid]==nums[l])            {l++; }        }return false; }};

and Search in rotated Sorted Array
Suppose a sorted array is rotated on 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 is given a target value to search. If found in the array is return its index, otherwise return-1.
This topic only need to change the parameters returned to AC.

classSolution { Public:intSearch vector<int>& Nums,intTarget) {intL=0, R=nums.size ()-1; while(L&LT;=R) {intMid= (L+R)/2;if(Nums[mid]==target)returnMidElse if(Nums[mid]>nums[l]) {if(Target>=nums[l]&&target<nums[mid]) r=mid-1;ElseL=mid+1; }Else if(Nums[mid]<nums[l]) {if(Target>nums[mid]&&target<=nums[r]) l=mid+1;Elser=mid-1; }Else if(Nums[mid]==nums[l])            {l++; }        }return-1; }};

Bayi. Search in rotated Sorted Array II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.