LeetCode33. 搜索旋转排序数组

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

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页