您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
描述
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。