search-in-rotated-sorted-array-ii

https://www.nowcoder.com/practice/d942d1aabf5549b0b53af55f1d4432e4?tpId=46&tqId=29097&tPage=4&rp=4&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

思路一:顺序查找即可

思路二:二分查找。


class Solution {
public:
    bool search(int A[], int n, int target) {
        if(A == nullptr || n <= 0)
			return false;
		int left = 0, right = n - 1;

		while(left <= right){
		
			int mid = left + ((right - left) >>1);
			if(A[mid] == target)
				return true;

			if(A[mid] > A[left]){//left-mid是升序序列
			
				if(target >= A[left] && target < A[mid])//target在left-mid
					right = mid - 1;
				else
					left = mid + 1;

			}
			else if(A[mid] < A[left]) {//left-mid不是升序
				if(target > A[mid] && target <= A[right])//在mid-right之间
					left = mid + 1;
				else
					right =  mid - 1;
			
			
			}
			else
				left++;///!!!!!注意A[mid]等于A[left]的时候不能排除哪一半数字了,只能left++!!!

		}

		return false;


    }


};

 

上一篇:给自己八年前的“网红面经”写个续篇


下一篇:论美妙的共鸣