LeetCode Search in Rotated Sorted Array solution, leetcoderotated

Source: Internet
Author: User

LeetCode Search in Rotated Sorted Array solution, leetcoderotated

Suppose an array sorted in ascending order is rotated at some unknown
Unknown to you beforehand.

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

Chinese:

Suppose there is an array in order to rotate by unknown axis of rotation (for example, 0 1 2 4 5 6 7 may become 4 5 6 7 0 1 2 ).
If you find the target value in the array and return the index position in the array, otherwise-1 is returned.

Solution:
The main idea is binary search. Although it is a rotating array, it is still satisfied. After finding the mid value, you can determine whether the mid value is greater than start to exclude half of the value of the array.

// The main idea is to use the public class Solution {public int search (int [] A, int target) {if (A = null |. length = 0) {return-1;} int start = 0; int end =. length-1; int mid; while (start + 1 <end) {mid = start + (end-start)/2; if (A [mid] = target) {return mid;} if (A [start] <A [mid]) {if (A [start] <= target & target <= A [mid]) {end = mid;} else {start = mid;} else {if (A [mid] <= target & target <= A [end]) {start = mid;} else {end = mid ;}} if (A [start] = target) {return start ;}if (A [end] = target) {return end;} return-1 ;}}

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.