日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[LeetCode] Search in Rotated Sorted Array

發(fā)布時間:2023/12/9 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] Search in Rotated Sorted Array 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

二分 : 判斷條件 當a[left] <= a[mid]時,可以肯定a[left..mid]是升序的

循環(huán)有序 一共有以下兩種情況

  第一種

   ?/

  /

 /

/   

     / 

    / 

條件:?(A[mid] >= A[low]) ,low~mid 二分,mid~high 遞歸

第二種

  / 

 /

     ?  /

      /  

     /

    / 

條件:?(A[mid] < A[low]) ,low~mid 二分,mid~high 遞歸

1 class Solution { 2 public: 3 int binarySearch(int A[], int low, int high, int target) 4 { 5 int mid = (high+low)/2; 6 7 if(low <= high) 8 { 9 if(target == A[mid]) 10 return mid; 11 else if(target > A[mid]) 12 return binarySearch(A, mid+1, high, target); 13 else 14 return binarySearch(A, low, mid-1, target); 15 } 16 return -1; 17 } 18 19 int search(int A[], int n, int target) 20 { 21 return search(A, 0, n-1, target); 22 } 23 24 int search(int A[], int low, int high, int target) 25 { 26 27 int mid = (high+low)/2; 28 29 if(low > high) 30 return -1; 31 32 if(A[mid] == target) 33 return mid; 34 35 if(A[mid] >= A[low]) // the pivot is in the bottom half 36 { 37 if(target >= A[low] && target < A[mid]) // target in the first half 38 { 39 return binarySearch(A, low, mid-1, target); 40 } 41 else // target in the bottom half 42 { 43 return search(A, mid+1, high, target); 44 } 45 } 46 else // the pivot is in the first half 47 { 48 if(target >= A[mid+1] && target <= A[high]) // target in the bottom half 49 { 50 return binarySearch(A, mid+1, high, target); 51 } 52 else // target in the first half 53 { 54 return search(A, low, mid-1, target); 55 } 56 } 57 } 58 };

?

迭代:

判讀條件和上面一樣

?

1 class Solution { 2 public: 3 bool search(int A[], int n, int target) { 4 int low = 0; 5 int high = n-1; 6 int mid ; 7 8 9 while(low<=high) 10 { 11 mid= (low + high)/2; 12 13 if(A[mid]==target) 14 { 15 return true; 16 } 17 18 if(A[low]<=A[mid]) // the pivot is in the bottom half 19 { 20 if(A[low]<=target && target < A[mid]) //target in the first half 21 high = mid-1; 22 else 23 low = mid+1;//target in the bottom half 24 } 25 else // the pivot is in the first half 26 { 27 if(A[mid] < target && target <= A[high])// the pivot is in the first half 28 low = mid+1; 29 else //target in the first half 30 high = mid-1; 31 } 32 33 } 34 return false; 35 36 } 37 };

?

轉(zhuǎn)載于:https://www.cnblogs.com/diegodu/p/3788663.html

總結(jié)

以上是生活随笔為你收集整理的[LeetCode] Search in Rotated Sorted Array的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。