如何求max:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
if( grid.size() ==0)
{
return 0 ;
}
int ret =0;
int m = grid.size();
int n = grid[0].size();
vector<vector<bool>> v( m , vector<bool> (n,false));
visited =v ;
for( int i =0 ; i< m ; i++)
{
for( int j =0 ; j< n ;j++)
{
if( grid[i][j]==1 && visited[i][j] ==false)
{
visited[i][j]=true ;
//开始宽搜
int a= BFS(grid ,i ,j);
cout<<"a:"<<a <<endl;
ret =max(ret ,a);
}
}
}
return ret;
}
class Solution
{
public:
int minOperations(vector<int>& nums, int x)
{
//找出最长的子数组的长度,所有元素的和为sum-x ,sum是整个数组的和
int sum =0;
for(auto e:nums)
{
sum+= e;
}
int target = sum-x ;
//边界情况
if(target <0)
{
return -1 ;
}
int m = 0; //m是子数组的和
int ret = -1 ;
for( int left = 0 , right =0 ; right <=nums.size()-1 ; right++)
{
//进窗口
m+= nums[right];
//判断
while ( m > target )
{
//出窗口
m-=nums[left];
left++;
}
if( m ==target)
{
ret = max(ret, right - left+1 );
}
}
if(ret==-1) //没有操作数
{
return -1 ;
}
return nums.size() - ret ;
}
};
class Solution
{
public:
int maxArea(vector<int>& height)
{
//利用单调性,使用双指针解决问题 ,O(N)
int left = 0;
int right = height.size() - 1;
int ret = 0;
while (left < right)
{
int v = min(height[left], height[right]) * (right - left);//计算容积
ret = max(ret, v);
//移动指针,谁小移动谁
if (height[left] < height[right])
{
left++;
}
else//height[left] >= height[right]
{
right--;
}
}
return ret;
}
};
如何求min
class Solution
{
public:
int minSubArrayLen(int target, vector<int>& nums)
{
//利用单调性 ,使用“同向双指针” -滑动窗口
//1、进窗口
//2、判断
//3、出窗口
int len = INT_MAX;
long long sum = 0;
for (int left = 0, right = 0; right <= nums.size() - 1;right++ )
{
sum += nums[right];
while(sum>=target)
{
len = min(len, right - left + 1);
sum -= nums[left];
left++;
}
}
return len == INT_MAX ? 0 : len;
}
};
class Solution {
public:
int findMinDifference(vector<string>& t) {
int n = t.size();
if(n>24*60)
return 0;
sort(t.begin(),t.end());
int pre = getNumber(t[0]);
int now,ans = 1440;
for(int i = 1;i<n;i++)
{
now = getNumber(t[i]);
ans = min(ans,now-pre);
pre = now;
}
ans = min(ans,getNumber(t[0])-getNumber(t[n-1])+1440);
return ans;
}
int getNumber(string & s)
{
return (((s[0]-'0')*10+s[1]-'0')*60+((s[3]-'0')*10+s[4]-'0'));
}
};