meaning of the title
Give an ordered array, and then swap the front and back halves from one location of the array. Now let's give a number k, find where k appears in the array, and if it doesn't, return to - 1.
thinking
Algorithm 1
Draw a picture. In fact, there are two situations: the first half is long or the second half is long, and then discuss them in several situations.
The results of the discussion are as follows:
-
k>am:
- am>ar:right
-
am<ar:
- k<ar:right
- k>ar:left
-
k<am:
- am<ar:left
-
am>ar:
- k<ar:right
- k>ar:left
Then take the equal sign to judge it.
Algorithm 2
The idea is the same as before. Find Minimum in Rotated Sorted Array
- k=am: Return to m.
-
k≠am:
-
Am < ar: It means that the right side is ordered.
- am<k≤ar:right
- else:left
-
Am > ar: It means that the left side is ordered.
- al≤k<ar:left
- else:right
-
Am < ar: It means that the right side is ordered.
Code
//algorithm1
class Solution {
public:
int search(vector<int>& a, int k) {
int n = a.size();
int l = 0, r = n - 1, m;
while (l <= r) {
m = l + (r - l >> 1);
if (a[m] == k) return m;
if (k > a[m]) {
if (a[m] > a[r]) l = m + 1;
else {
if (k == a[r]) return r;
if (k < a[r]) l = m + 1;
else r = m - 1;
}
} else {
if (a[m] < a[r]) r = m - 1;
else {
if (a[r] == k) return r;
else if (k < a[r]) l = m + 1;
else r = m - 1;
}
}
}
return -1;
}
};
//algorithm 2
class Solution {
public:
int search(vector<int>& a, int k) {
int n = a.size();
int l = 0, r = n - 1, m;
while (l <= r) {
m = l + (r - l >> 1);
if (a[m] == k) return m;
if (a[m] < a[r]) {
if (a[m] < k && k <= a[r]) l = m + 1;
else r = m - 1;
} else {
if (a[l] <= k && k < a[m]) r = m - 1;
else l = m + 1;
}
}
return -1;
}
};