SearchinRotatedSortedArray
描述
创新互联公司是一家专注于成都做网站、网站制作与策划设计,龙港网站建设哪家好?创新互联公司做网站,专注于网站建设十年,网设计领域的专业建站公司;建站业务涵盖:龙港等地区。龙港做网站价格咨询:18980820575
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#include 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[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的代码:
我自己编的程序基本上和他给的一样,说明自己还是有进步的,嘻嘻。。。。继续加油!
<完>
网站题目:SearchinRotatedSortedArray
转载注明:http://cdiso.cn/article/jsdpdd.html