[Leetcode] 033. Search in rotated Sorted Array (hard) (C + +)

Source: Internet
Author: User

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode

033. Search in rotated Sorted Array (hard) links

Title: https://leetcode.com/problems/search-in-rotated-sorted-array/
Code (GitHub): Https://github.com/illuz/leetcode

Test Instructions

Find a number in an ordered array that has been rotated.
For example 4 5 6 7 0 1 2 , a "rotated ordered array".

Analysis

This is the distortion of the pure binary search.
Because the rotation is not good positioning, so when looking for the time can be judged whether an interval is completely ordered or has been rotated, and then classified discussion.

Code

C++:

Class Solution {Public:int search (int a[], int n, int target) {int left = 0, right = N;while (left! = right) {int mid = (l EFT + right)/2;if (A[mid] = target) return mid;if (A[mid] >= A[left]) {//[Left~mid] is unrotated sortedif (A[left] & lt;= Target && Target < A[mid]) right = Mid;elseleft = mid + 1;} else {//[mid~right] is unrotated sortedif (A[mid] < target && target <= a[right-1]) left = mid + 1;elserig HT = mid;}} return-1;}};


[Leetcode] 033. Search in rotated Sorted Array (hard) (C + +)

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.