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.