Leetcode: Search in rotated sorted Array)

Source: Internet
Author: User

Question:

Suppose a sorted array is rotated at some unknown to you beforehand.

(I. e .,0 1 2 4 5 6 7Might become4 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.

Note:

1) binary search for sorted Arrays

2) locate critical points

Implementation:

I. My code:

1 class solution {2 public: 3 int search (int A [], int N, int target) {4 If (n = 0 | n = 1 & A [0]! = Target) Return-1; 5 if (a [0] = target) return 0; 6 int I = 1; 7 while (A [I-1] <A [I]) I ++; 8 9 int pre = binary_search (A, 0, I, target); 10 int Pos = binary_search (A, I, n-I, target ); 11 return pre =-1? POs: Pre; 12} 13 private: 14 int binary_search (int * B, int Lo, int Len, int goal) 15 {16 int low = lo; 17 int high = lo + len-1; 18 while (low <= high) 19 {20 int middle = (low + high)/2; 21 if (Goal = B [Middle]) // find and return index22 return middle; 23 else if (B [Middle] <goal) // on the right side 24 low = middle + 1; 25 else // on the left side 26 high = middle-1; 27} 28 return-1; // No, -129} 30 };

2. Open source code on the Internet:

 

 1 class Solution { 2 public: 3     int search(int A[], int n, int target) { 4         int first = 0, last = n-1; 5         while (first <= last)  6         { 7             const int mid = (first + last) / 2; 8             if (A[mid] == target) 9                 return mid;10             if (A[first] <= A[mid]) 11             {12                 if (A[first] <= target && target < A[mid])13                    last = mid-1;14                 else15                    first = mid + 1;16             } 17             else 18             {19                 if (A[mid] < target && target <= A[last])20                     first = mid + 1;21                 else22                     last = mid-1;23             }24         }25         return -1;26     }27 };

 

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.