您好,登錄后才能下訂單哦!
描述
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
2.1 數組 5
(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.
binary.h
#include <iostream> #include <assert.h> class Solution { public: int search(int A[], int n, int value) { assert(A); int start = 0; int end = n - 1; while (start<=end){ int mid = (end - start) / 2 + start; if (A[mid] == value) return mid; if (A[start]<=A[mid]){//orders if (value<A[mid]&&value>=A[start]) end = mid - 1; else start = mid + 1; } else{//disorder if (value>A[mid]&&value<=A[end]) start = mid + 1; else{ end = mid - 1; } } } return -1; } };
binary.cpp
#include "binary.h" using namespace std; int main() { int a[9] = { 7, 8, 9, 0, 1, 2, 4, 5, 6 }; Solution s1; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 7) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 8) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 9) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 0) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 1) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 2) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 4) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 5) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 6) << endl; cout << s1.search(a, sizeof(a) / sizeof(a[0]), 3) << endl; system("pause"); return 0; }
運行結果:
以下是leetcode_cpp的代碼:
我自己編的程序基本上和他給的一樣,說明自己還是有進步的,嘻嘻。。。。繼續加油!
<完>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。