class Solution {
public:
int search(vector<int>& nums, int target) {
int n = nums.size();
int l = 0;
int r = n-1;
while(l <= r)
{
int mid = l+(r-l)/2;
if(nums[mid] == target)
return mid;
//首先判断前半段是否是单调的,如果前半段不单调,那么后半段一定单调
if(nums[l] <= nums[mid])
{
if(nums[l] <= target && target < nums[mid])
r = mid - 1;
else//排除掉
l = mid + 1;
}
else
{
if(nums[mid] < target && target <= nums[r])
l = mid + 1;
else//排除掉
r = mid - 1;
}
}
return -1;
}
};
class Solution {
public:
bool search(vector<int>& nums, int target) {
int n = nums.size();
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] == target) {
return true;
} else if (nums[mid] > nums[r]) { // 说明在左半边 在[0, mid-1]进行查找
if (target >= nums[l] && target < nums[mid]) {
r = mid;
} else {
l = mid + 1;
}
} else if (nums[mid] < nums[r]) {
if (target > nums[mid] && target <= nums[r]) {
l = mid + 1;
} else {
r = mid;
}
} else { // 处理重复元素
r--;
}
}
if (nums[l] == target) return true;
return false;
}
};
class Solution {
public:
int findMin(vector<int>& nums) {
if(nums.size()==1) return nums[0]; // 注意数组长度为1的情况
int left = 0, right = nums.size()-1;
if(nums[right] > nums[left]) return nums[left]; // 数组没有旋转,直接返回最小值nums[left]
int mid = 0;
while(left<=right){
mid = left+(right-left)/2;
if(nums[mid] > nums[mid+1]) return nums[mid+1];
if(nums[mid-1] > nums[mid]) return nums[mid];
if(nums[left]<nums[mid]) left = mid+1; // 这里也可以写成nums[left]<=nums[mid]
else if(nums[mid]<nums[right]) right = mid-1; // 但由于数组中没有重复元素,所以不可能等于,写<就行
}
return nums[mid];
}
};
// c++
class Solution {
public:
int climbStairs(int n) {
vector<int> res;
res.push_back(1);
res.push_back(2);
if(n == 1)
return res[0];
if(n == 2)
return res[1];
else{
for(int i=2;i<n;i++){
res.push_back(res[i-1] + res[i-2]);
}
return res[n-1];
}
}
};
class Solution {
public:
int fib(int n)
{
return n <= 1 ? n : fib(n - 1) + fib(n - 2);
}
};
class Solution {
public:
int tribonacci(int n) {
if (n < 2) return n;
int first = 0, second = 1, third = 1;
for (int i = 2; i < n; ++i) {
int t = first;
first = second;
second = third;
third = t + first + second;
}
return third;
}
};
class Solution {
public int fib(int n) {
if(n == 0) return 0;
int[] dp = new int[n + 1];
dp[0] = 0;
dp[1] = 1;
for(int i = 2; i <= n; i++){
dp[i] = dp[i-1] + dp[i-2];
dp[i] %= 1000000007;
}
return dp[n];
}
}