LeetCode33. 搜尋旋轉排序陣列

Ember_Sky發表於2020-09-26
//LeetCode33. 搜尋旋轉排序陣列
class Solution {
public:
  vector<int>s;
  int it;
  void dfs(int l, int r) {
    if (l == r) {
      it = l + 1;
      return;
    }
    int mid = (l + r) >> 1;
    if (s[l] <= s[mid] && s[mid + 1] <= s[r]) it = mid + 1;
    else if (s[l] <= s[mid]) dfs(mid + 1, r);
    else if (s[mid + 1] <= s[r]) dfs(l, mid);
  }
  int ans;
  int get(int x) {
    return (x + it) % s.size();
  }
  void fin(int tar, int l, int r) {
    if (l == r) {
      if (s[get(l)] == tar) ans = l;
      else ans = -1;
      return;
    }
    int mid = (l + r) >> 1;
    if (s[get(mid)] >= tar) fin(tar, l, mid);
    else fin(tar, mid + 1, r);
  }
  int search(vector<int>& nums, int tar) {
    s = nums;
    if (s.front() < s.back()) it = 0;
    else dfs(0, s.size() - 1);
    fin(tar, 0, s.size() - 1);
    return ans == -1 ? -1 : get(ans);
  }
};

相關文章