[Leetcode] #34 Search in rotated Sorted Array

Source: Internet
Author: User

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.

Assume no duplicate exists in the array.

This paper uses the idea of binary algorithm, to determine whether the target is in the first half or the second half, and then separate search. Time: 7ms. The code is as follows:

classSolution { Public:    intSearch (vector<int>& Nums,intFintLinttarget) {        if(f>l)return-1; if(target = =Nums[f])returnF; if(target = =Nums[l])returnl; intMID = f + (L-F)/2; if(target = =Nums[mid])returnmid; if(Nums[f] = = Nums[l] && nums[f] = =Nums[mid]) {             for(inti = f; i<l; i++){                if(Nums[i] = =target)returni; }            return-1; }        if(Nums[f] <target) {            if(nums[f]<nums[mid]&&target>Nums[mid])returnSearch (Nums, Mid +1, L, Target); Else                returnSearch (Nums, F, mid-1, Target); }        Else if(nums[l]>target) {            if(Nums[mid]<nums[l] && Target <Nums[mid])returnSearch (Nums, F, mid-1, Target); Else                returnSearch (Nums, Mid +1, L, Target); }        return-1; }    intSearch (vector<int>& Nums,inttarget) {        if(nums.size () = =0)            return-1; returnSearch (Nums,0, Nums.size ()-1, Target); }};

[Leetcode] #34 Search in rotated Sorted Array

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.