leetcode-题4
只有一个旋转点,有二分法可以降低复杂度。
二分过后肯定有半边是有序的,我们假设数组是升序的数组,中间有一个旋转点。
解法一:
#include <iostream> #include <vector> using namespace std; int main() { int a[6] = { 11,12,3,4,5,9 }; int le = 0; int r = 5; int tar; cin >> tar; while (le <= r) { int mid = le + (r - le) / 2; if (a[mid] == tar) { cout << 1 << ' '; break; } if (a[le] <= a[mid])//the left is order { if (a[le] <= tar&&tar < a[mid]) r = mid - 1; else le = mid + 1; } else {//the right is order if (a[mid] < tar&&tar <= a[r]) le = mid + 1; else r = mid - 1; } } if (le > r)cout << -1 << ' '; system("pause"); return 0; }
解法2:
#include <iostream> #include <vector> using namespace std; int dfs(const vector<int>&num, int le, int re, int tar) { int mid = le + (le + re) / 2; if (le > re)return -1; if (num[mid] == tar)return 1; if (num[le] <= num[mid]) { if (num[le] <= tar&&tar < num[mid]) { re = mid - 1; dfs(num, le, re, tar); } else { le = mid + 1; dfs(num, le, re, tar); } } else { if (num[mid] < tar&&tar < num[re]) { le = mid + 1; dfs(num, le, re, tar); } else { re = mid - 1; dfs(num, le, re, tar); } } } int main() { int tar; cin >> tar; int a[6] = { 8,9,1,2,3,4 }; vector<int>num(a,a + 6); int res = dfs(num, 0, 5, tar); cout << res << endl; system("pause"); return 0; }