The problem is to reverse a sort of array part, causing the array to become part of the ordered two parts, now given a target, and finally find out the target subscript, if not exist then return-1, the topic meaning is still very good understanding, but the solution is indeed more troublesome. Why bother? Because the way to iterate over an array doesn't apply, and it doesn't make sense!
So we have to open up another path, we usually find an ordered array when the most used method is the binary search method, then the question can be used to find the two points? The answer is yes, and this is the way to find the target's subscript. Ideas are as follows:
Although the array is reversed, not the whole order, but it is still partially ordered, for example: "4 5 6 7 0 1 2", we can see the array of two parts or orderly, we can use this to solve, said here I think there is no need to explain more, directly look at the code:
Class Solution {Public:int search (vector<int>& nums, int target) {//This question is for a sorted array, but the contents of the array are moved in parallel, as shown in the example above, now Find the subscript int len = nums.size () corresponding to the Tagert; Special case first Consider if (len = = 0) {return-1;} if (len = = 1 && target!=nums[0]) {return-1;} Normally, you should not be able to traverse the array bar, it is meaningless, it should not pass, although the order is disrupted, but the part is ordered, we still use the binary search int left = 0; int right = len-1; int mid = 0; while (left <= right) {mid = left + (right-left)/2; if (target = = Nums[left]) {return left; } if (target = = Nums[right]) {return right; } if (target = = Nums[mid]) {return mid; }//Two min find if (Nums[mid] >= Nums[left]) {//left ordered if (Target > Nums[left] && target < Nums[mid]) { right = Mid-1; } else {left = mid + 1; }} else {//right ordered if (Target > Nums[mid] && target < Nums[righ T]) {left = mid + 1; } else {right = Mid-1; }}} return-1; }};
The results are as follows, I am directly using this solution, the method of traversal did not try, I think should be unable to pass, this type of question is the extension of the two-point search.
Written question 46. Leetcode OJ (33)