//时间复杂度:O(n)
//空间复杂度:O(1)
class Solution {
public:
int maxProduct(vector<int>& nums) {
int maxn=-1,maxnn=-1;
for(int i=0; i < nums.size(); i++){
if(nums[i] > maxn){
maxnn=maxn;
maxn=nums[i];
}else if(nums[i] > maxnn){
maxnn=nums[i];
}
}
return (maxn-1)*(maxnn-1);
}
};
//时间复杂度:O(n)
//空间复杂度:O(1)
class Solution {
public:
int findMaxConsecutiveOnes(vector<int>& nums) {
int count=0,maxn=-1;
for(int i=0;i<nums.size();i++){
if(nums[i]==1){
count++;
}else{
maxn=max(maxn,count);
count=0;
}
}
maxn=max(count,maxn);
return maxn;
}
};
//时间复杂度:O(logn)
//空间复杂度:O(1)
class Solution {
public:
int findMin(vector<int>& nums) {
int left=0,right=nums.size()-1;
while(left<right){
int mid=(left+right)/2;
if(nums[mid]<nums[right]){
right=mid;
}else{
left=mid+1;
}
}
return nums[left];
}
};
//时间复杂度:O(logn)
//空间复杂度:O(1)
class Solution {
public:
int findMin(vector<int>& nums) {
int left=0,right=nums.size()-1;
while(left<right){
int mid=(left+right)/2;
if(nums[mid]<nums[right]){
right=mid;
}else if(nums[mid]>nums[right]){
left=mid+1;
}else{
right-=1;
}
}
return nums[left];
}
};
//时间复杂度:O(logn)
//空间复杂度:O(1)
class Solution {
public:
int minArray(vector<int>& numbers) {
int left=0,right=numbers.size()-1;
while(left<right){
int mid=(left+right)/2;
if(numbers[mid]<numbers[right]){
right=mid;
}else if(numbers[mid]>numbers[right]){
left=mid+1;
}else{
right-=1;
}
}
return numbers[left];
}
};
//时间复杂度:O(n)
//空间复杂度:O(1)
class Solution {
public:
int thirdMax(vector<int>& nums) {
long a=LONG_MIN,b=LONG_MIN,c=LONG_MIN;
for(int i=0;i<nums.size();i++){
if(nums[i]>a){
c=b;
b=a;
a=nums[i];
}else if(nums[i]>b&&nums[i]<a){
c=b;
b=nums[i];
}else if(nums[i]>c&&nums[i]<b){
c=nums[i];
}
}
return c==LONG_MIN?a:c;
}
};
//时间复杂度:O(n)
//空间复杂度:O(1)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n=prices.size();
int minloc=0x3f3f3f,maxw=0;
for(int i=0;i<n;i++){
maxw=max(maxw,prices[i]-minloc);
minloc=min(minloc,prices[i]);
}
return maxw;
}
};
//时间复杂度:O(n)
//空间复杂度:O(1)
class Solution {
public:
int maximumProduct(vector<int>& nums) {
int max1=-1e5-5,max2=-1e5-5,max3=-1e5-5;
int min1=1e5+5,min2=1e5+5;
for(int i=0;i<nums.size();i++){
if(nums[i]<min1){
min2=min1;
min1=nums[i];
}else if(nums[i]<min2){
min2=nums[i];
}
if(nums[i]>max1){
max3=max2;
max2=max1;
max1=nums[i];
}else if(nums[i]>max2){
max3=max2;
max2=nums[i];
}else if(nums[i]>max3){
max3=nums[i];
}
}
return max(max1*max2*max3,max1*min1*min2);
}
};
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_47511190/article/details/120641811
内容来源于网络,如有侵权,请联系作者删除!