LeetCode -- Search in Rotated Sorted Array, rotatedsortedarray

Source: Internet
Author: User

LeetCode -- Search in Rotated Sorted Array, rotatedsortedarray
Search in Rotated Sorted Array:

Most of the questions you search online are incorrect.
As follows:
Use while (first! = Last) this loop,
-1.
When we do this first = last, it will jump out of the loop and cause an error.
The correct method should be do {} while (first! = Last ).

Ideas:

The array is as follows: Large -- small -- medium

Boundaries are divided into four situations:

Left <mid: whether the key is in (left, mid). If it is in, right = mid-1; if not, left = mid + 1; left> mid: whether the key is in (mid, right). If the key is in, left = mid + 1; if not, right = mid-1;
Efficiency:

Time complexity O (log n), space complexity O (1)

C code
#include <iostream>using namespace std;int search(int* nums, int numsSize, int target) {    int left = 0;    int right = numsSize-1;    do{        int mid = (left+right)/2;        if(nums[mid]==target) return mid;        if(nums[left]<=nums[mid]){            if(nums[left]<=target && target<nums[mid]){                right = mid-1;            }else{                left = mid+1;            }        } else {            if(nums[mid]<target && target<=nums[right]){                left = mid+1;            }else{                right = mid-1;            }        }    }while(left<=right);            return -1;}int main(int argc, char *argv[]) {    int arr[] = {3,1,2};    int result = search(arr,3,2);    printf("%d", result);    return 0;}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.