首页 > 代码库 > Search in Rotated Sorted Array
Search in Rotated Sorted Array
本题的思路是二分查找,关键是怎么用二分查找。通过middle值和数组尾部的值比较,可以确定start-Middle和middle-end,这两部分那一部分是有序的,有序的数组是可以用二分查找的。
class Solution {public: int search(int A[], int n, int target) { if(n == 0) return 0; int middle,end,start; start = 0; end = n-1; middle = (start + end)/2; int result; while(start <= end) { if(A[middle] < A[end]) { result = findbinarysearch(A,middle,end,target); if(result !=-1) return result; end = middle -1; middle = (start+ end)/2; } else if(A[middle] > A[end]) { result = findbinarysearch(A,start,middle,target); if(result !=-1) return result; start = middle +1 ; middle = (start+ end)/2; } else { if(A[middle] == target) return middle; else return -1; } } return -1; } int findbinarysearch(int A[],int start, int end, int target) { int middle = (start + end)/2; while(start <= end) { if(A[middle] < target) { start = middle +1; middle = (start + end)/2; } else if(A[middle] > target) { end = middle -1; middle = (start + end)/2; } else { return middle; } } return -1; }};
Search in Rotated Sorted Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。