题目链接: 977. 有序数组的平方
个人题解如下:使用双指针(前后),谁的平方最大,赋值到新Vector的最后(一个一个往前填)
class Solution
{
public:
vector<int> sortedSquares(vector<int>& nums)
{
vector<int> ret(nums.size(), 0);
int begin = 0;
int end = nums.size() - 1;
int index = end;
while ((begin <= end) && (nums.size() > 0))
{
if ((nums[begin] * nums[begin]) < (nums[end] * nums[end]))
{
ret[index] = (nums[end] * nums[end]);
end --;
}
else
{
ret[index] = (nums[begin] * nums[begin]);
begin ++;
}
if (index > 0)
{
index --;
}
}
return ret;
}
};
题目链接: 209.长度最小的子数组
个人题解如下:同样使用左右双指针,退出条件是右指针超过长度,右指针向右移动,当满足>=target条件后,左指针向右移动,记录本次最小值,直到退出。
class Solution
{
public:
int minSubArrayLen(int target, vector<int>& nums)
{
int ret = INT_MAX;
int left = 0, right = 0;
int sum = 0;
while (right < nums.size())
{
sum += nums[right];
while (sum >= target)
{
ret = min(ret, (right - left + 1));
sum -= nums[left ++];
}
right ++;
}
return (ret == INT_MAX? 0 : ret);
}
};
题目链接: 59.螺旋矩阵II
个人题解如下::::::😃
class Solution
{
public:
vector<vector<int>> generateMatrix(int n)
{
vector<vector<int>> array(n, vector<int>(n, 0));
int i = 0, j = -1, k = 0;
int index = 1;
int max = n;
array[0][0] = 1;
while (max > 0)
{
if (index < (n * n))
{
j ++;
array[i][j] = index;
index ++;
}
else
{
break;
}
k = 0;
while (k < (max - 1))
{
j ++;
array[i][j] = index;
index ++;
k ++;
}
k = 0;
while (k < (max - 1))
{
i ++;
array[i][j] = index;
index ++;
k ++;
}
k = 0;
while (k < (max - 1))
{
j --;
array[i][j] = index;
index ++;
k ++;
}
k = 0;
while (k < (max - 2))
{
i --;
array[i][j] = index;
index ++;
k ++;
}
if (max > 2)
{
max -= 2;
}
else
{
max = 0;
}
if (max == 1)
{
j ++;
array[i][j] = index;
}
}
return array;
}
};