Leetcode 33 - Search in Rotated Sorted Array (dichotomy)

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:

  1. k>am​:
    1. am>ar:right
    2. am<ar:
      1. k<ar:right
      2. k>ar:left
  2. k<am:
    1. am<ar:left
    2. am>ar:
      1. k<ar:right
      2. 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

  1. k=am: Return to m.
  2. k≠am:
    1. Am < ar: It means that the right side is ordered.
      1. am<k≤ar:right
      2. else:left
    2. Am > ar: It means that the left side is ordered.
      1. al≤k<ar:left
      2. else:right

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;
    }
};

Posted by andyg2 on Thu, 14 Feb 2019 09:09:19 -0800