力扣
977有序数组的平方
暴力写法:
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
for(int i =0;i<nums.size();i++)
{
nums[i] = nums[i]*nums[i];
}
sort(nums.begin(),nums.end());
return nums;
}
};
修改后:
双指针写法,谁大谁走
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
std::vector<int> res(nums.size(),0);
int left =0;
int right = nums.size()-1;
int k = nums.size()-1;
while(left <= right)
{
if(nums[left]*nums[left] <= nums[right]*nums[right])
{
res[k] = nums[right]*nums[right];
right--;
k--;
}
else if(nums[left]*nums[left]>nums[right]*nums[right])
{
res[k] = nums[left]*nums[left];
left++;
k--;
}
}
return res;
}
};
自己没写对,看的答案
重点在循环中止条件与最小长度
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int res = INT32_MAX;
int length =0;
int slow =0;
int sum =0;
for(int fast =0;fast < nums.size();fast++)
{
sum +=nums[fast];
length++;
while(sum >=target)
{
res = res < length ? res : length;
sum -=nums[slow];
slow++;
length--;
}
}
return res == INT32_MAX ? 0 : res;
}
};
不会
小声bb一句,实际项目中真的会遇到到这种问题吗
周末再好好看一下此题
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n,vector<int>(n,0));
int startx = 0;
int starty =0;
int mid = n/2;
int loop = n/2;
int offset = 1;
int count = 1;
int i,j;
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 != 0)
{
res[mid][mid] = count++;
}
return res;
}
};