977. 有序数组的平方
题目链接:977. 有序数组的平方
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size();
while(left < right){
int middle = (left + right)/2;
if(nums[middle]<target){
left = middle+1;
}else if(nums[middle]>target){
right = middle;
}else return middle;
}
return -1;
}
};
209.长度最小的子数组
题目链接:
209.长度最小的子数组
滑动窗口
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result = INT32_MAX;
int i = 0, sum = 0;
for(int j = 0; j < nums.size(); j++){
sum += nums[j];
while(sum >= target){
int subL = j - i + 1;
result = subL < result ? subL : result;
sum -= nums[i++];
}
}
return result == INT32_MAX ? 0 : result;
}
};
59.螺旋矩阵II
59.螺旋矩阵II
边界控制
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int startx = 0;
int starty = 0;
int loop = n/2;
int offset = 1;
int i = startx;
int j = starty;
int count = 1;
vector<vector<int>> res(n, vector<int>(n, 0));
while(loop--){
for(j = starty; j < n - offset; j++){
res[startx][j] = count++;
}
for(i = startx ; i < n - offset; i++){
res[i][j] = count++;
}
for( ; j > starty; j--){
res[i][j] = count++;
}
for( ; i > startx; i--){
res[i][j] = count++;
}
startx++;
starty++;
offset++;
}
if(n % 2) res[n/2][n/2] = count++;
return res;
}
};