Search in Rotated Sorted Array

来源:互联网 发布:p2p监控软件 哪个最好 编辑:程序博客网 时间:2024/05/17 04:26

初阶。

Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(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.


进阶。

Follow up for ”Search in Rotated Sorted Array”: What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.


对于初阶。思路,采用二分查找。如果中间数大于最左边的数,那么左半部分必然有序,否则右半部分必然有序。通过目标数与有序部分的最大最小数比较,可以判断目标数到底属于哪一个部分。时间复杂度O(logn),空间复杂度O(1).

class Solution{public:int search(int A[],int n,int target){int first = 0,last = n;while(first != last){int mid = (first + last)/2;if (A[mid] == target)return mid;if(A[first] <= A[mid]){if (A[first] <= target && target < A[mid])last = mid;elsefirst = mid + 1;}else{if (A[mid] < target && target <= A[last-1])first = mid + 1;elselast = mid;}}return -1;}};



对于进阶。思路,和初阶的区别在于。如果A[m]>=A[l],不能保证[l,m]是有序的。比如[2,4,2,2,2].这种情况下可以拆分为两个条件,1)A[m]>a[l],则[l,m]必然有序;2)如果A[m]==a[l],那么就l++,往下看。

int search_2(int A[],int n,int target){int first = 0,last =n;while(first != last){int mid = (first + last)/2;if(A[mid] == target)return mid;if(A[first] < A[mid]){if(A[first]<=target && target < A[mid])last = mid;elsefirst = mid + 1;}else if(A[first] > A[mid]){if(A[mid] < target && target <= A[last-1])first = mid + 1;elselast = mid;}else//skip duplicate onefirst ++;}return -1;}


0 0
原创粉丝点击