Title: Given a rotating array and an integer, determine if the integer is in the array. The definition of a rotating array is to move several elements of the starting part of the array to the end of the array. This problem assumes that there are no duplicate elements in the array.
Idea: the previously written judgment was particularly complex and then went wrong. Read the online puzzle, so think about it: by judging the size of the mid element, we know that the sequence of the left of the mid-order or the right sequence. Each time a target element is compared to an ordered sequence of first and last elements, if in that ordered sequence, the corresponding pointer is moved so that it is found in the sequence, otherwise the target element moves the corresponding pointer in another sequence.
It is important to note that you need to maintain this feature regardless of whether you open the right or closed interval. When using left closed right open interval, the tail element is remembered-1, nums[last-1].
Related: A similar question in the offer of a sword is the minimum value of the rotation array. The two ideas are not quite the same. The minimum value is to maintain two pointers P1 and P2,P1 always point to the first increment sequence, P2 always points to the second increment sequence, and the mid element compares with the end-to-end element, moving P1 or P2 pointers. When the final P1 and P2 are adjacent, P2 points to the minimum value. Wait a minute..
classSolution { Public: intSearch (vector<int>& Nums,inttarget) { intfirst=0; intlast=nums.size (); while(first<Last ) { intmid=first+ (Last-first)/2; if(Nums[mid]==target)returnmid; if(nums[first]<Nums[mid]) {//Left Order if(Nums[first]<=target && target<=Nums[mid]) last=mid; Else First=mid+1; } Else {//Right Order if(Nums[mid]<=target && target<=nums[last-1])//since it's a left-right open range, it's supposed to be last-1.First=mid+1; Else Last=mid; } } return-1; }};
Leetcode Search in rotated Sorted Array