前言:今天去校醫(yī)院拔了兩顆牙,太痛了,今天寫的博客就比較水。
1、有序數(shù)組的平方(雙指針法)
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int k = nums.size() - 1;
vector<int> result(nums.size(),0);//創(chuàng)造一個數(shù)組result長度與nums相同
for(int i = 0, j = nums.size() -1;i <= j;)
{
if(nums[i]*nums[i] < nums[j]*nums[j])
{
result[k--] = nums[j]*nums[j];
j--;
}else{
result[k--] = nums[i]*nums[i];
i++;
}
}
return result;
}
};
2、 長度最小的子數(shù)組(滑動窗口)
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int result = INT32_MAX;//返回值
int i = 0;//滑動窗口的起始位置
int sum = 0;//子數(shù)組中元素之和
int subLength = 0;//滑動窗口的長度
for(int j = 0;j < nums.size();j++)//將j設置成終止元素
{
sum += nums[j];
while(sum >= target)
{
subLength = j - i + 1;
sum -= nums[i];
i++;
result = result < subLength ? result : subLength;
}
}
return result == INT32_MAX ? 0 : result;
}
};
所謂滑動窗口,就是不斷的調(diào)節(jié)子序列的起始位置和終止位置,從而得出我們要想的結(jié)果。文章來源:http://www.zghlxwxcb.cn/news/detail-427327.html
3、 螺旋矩陣
文章來源地址http://www.zghlxwxcb.cn/news/detail-427327.html
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n,vector<int>(n,0));//使用vector容器定義一個二維數(shù)組
int startx = 0,starty = 0;//定義起始點坐標是(0,0)
int offset = 1;//設定偏移量為1
int count = 1;
int loop = n / 2;
int mid = n/2;
while(loop--)//偶數(shù),轉(zhuǎn)n/2圈;奇數(shù),轉(zhuǎn)n/2+1圈(等一會判斷一下)
{
int i = startx;
int j = starty;
//遵循左閉右開,設定有i行,j列
for(j = starty;j < n - offset;j++)// 從左到右處理
{
result[startx][j] = count++;
}
for(i = startx;i < n - offset;i++)// 從上到下處理
{
result[i][j] = count++;
}
for(;j > starty;j--)// 從右到左處理
{
result[i][j] = count++;
}
for(;i > startx;i--)// 從下到上處理
{
result[i][j] = count++;
}
startx++;
starty++;
offset++;
}
if(n % 2)
{
result[mid][mid] = count;
}
return result;
}
};
到了這里,關于代碼隨想錄day2|有序數(shù)組的平方、長度最小的子數(shù)組、螺旋矩陣的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!