977.有序数组的平方
题目链接:LeetCode题目链接 视频讲解:双指针法经典题目!LeetCode:977.有序数组的平方
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int size=nums.size();
for(int i=0;i<size;i++){
nums[i]*=nums[i];
}
sort(nums.begin(),nums.end());
return nums;
}
};
时间复杂度:O(n + nlogn)
核心思路:最大值仅有可能在左右两边取到
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int size=nums.size();
int k=size-1;
vector<int> ans(size,0);
for(int i=0,j=size-1;i<=j;){
if(nums[i]*nums[i]>nums[j]*nums[j]){
ans[k--]=nums[i]*nums[i];
i++;
}
else{
ans[k--]=nums[j]*nums[j];
j--;
}
}
return ans;
}
};
209.长度最小的子数组
题目链接:LeetCode题目链接 视频讲解:拿下滑动窗口! | LeetCode 209 长度最小的子数组
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result = INT32_MAX;
int sum = 0;
int subLength = 0;
for (int i = 0; i < nums.size(); i++) {
sum = 0;
for (int j = i; j < nums.size(); j++) {
sum += nums[j];
if (sum >= target) {
subLength = j - i + 1;
result = result < subLength ? result : subLength;
}
}
}
return result == INT32_MAX ? 0 : result;
}
};
- 解法二:滑动窗口
核心思想:不断变换左右窗口位置得到最小值
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result = INT32_MAX;
int sum = 0;
int i = 0;
int subLength = 0;
for(int j=0;j<nums.size();j++){
sum+=nums[j];
while(sum>=target){
subLength=j-i+1;
result=result<subLength?result:subLength;
sum-=nums[i++];
}
}
return result==INT32_MAX?0:result;
}
};
59.螺旋矩阵II
题目链接:LeetCode题目链接 视频讲解:一入循环深似海 | LeetCode:59.螺旋矩阵II 核心思想:找准循环边界条件,耐心调试,看准每次循环以后需要改变的条件
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n,0));
int loop=n/2;
int startx=0,starty=0;
int mid=n/2;
int count=1;
int i,j;
int offset=1;
while(loop--){
i = startx;
j = starty;
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+=1;
}
if(n%2){
res[mid][mid]=count;
}
return res;
}
};
|