代码随想录算法训练营第二天
一、有序数组的平方
这题比较容易就想到双指针的方法,在开始和末端设置两个指针来向中间移动,判断左右两个指针所指的对象平方大小,将大的那个移到新数组末端。
class Solution {
public:
vector<int> sortedSquares(vector<int>& nums) {
int leftIndex = 0, rightIndex = nums.size() - 1;
int i = nums.size() - 1;
vector<int> result = nums;
while(leftIndex <= rightIndex){
if(abs(nums[leftIndex]) < abs(nums[rightIndex])){
result[i--] = nums[rightIndex] * nums[rightIndex];
rightIndex--;
}
else{
result[i--] = nums[leftIndex] * nums[leftIndex];
leftIndex++;
}
}
return result;
}
};
二、长度最小的子数组
这道题一刷的时候试了好久没能通过,后面看了Carl哥的讲解理解了滑动窗口的思想,利用快慢指针的思想来构建一个可以滑动的窗口滑动窗口的精妙之处在于根据当前子序列和大小的情况,不断调节子序列的起始位置。从而将O(n^2)暴力解法降为O(n)。这次做的时候就比较容易解出来了。
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
// int slowIndex = 0, fastIndex = 0;
int sum = 0, sublength = INT32_MAX;
int minlength = INT32_MAX;
for(int fastIndex = 0, slowIndex = 0; fastIndex < nums.size(); fastIndex++){
sum += nums[fastIndex];
while(sum >= target){
sublength = fastIndex - slowIndex + 1;
sum -= nums[slowIndex++];
}
minlength = sublength < minlength? sublength:minlength;
}
return minlength == INT32_MAX? 0: minlength;
}
};
三、螺旋矩阵II
从这题开始之后的题就是一刷了,花了一段时间才发现循环的判断语句,通过判断他的拐角次数来终止循环,即拐角次数为2*n-1;而每次填充数据的时候,区间的起始位置和终止位置可以通过螺旋的圈数来判定。但要注意保证区间开闭一致。
一刷的代码,自己做的方法得分好低。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n,vector<int>(n, 0));
int i = 0, j = 0;
int count = 0;
int number = 1;
while(count < (2 * n)){
if(count % 4 == 0){
for(int i = j = count / 4; j <= n-1-(count/4); j++){
result[i][j] = number;
number +=1;
}
count++;
}
else if(count % 4 == 1){
for(int j = n-1-count/4, i = 1 + count / 4; i <= n-1-count/4; i++){
result[i][j] = number;
number +=1;
}
count++;
}
else if(count % 4 == 2){
for(int i = n-1-count/4, j = n - 2 - count/4; j >= count / 4; j--){
result[i][j] = number;
number +=1;
}
count++;
}
else{
for(int i = n-2-count/4, j = count / 4; i>=1 + count / 4; i--){
result[i][j] = number;
number +=1;
}
count++;
}
}
return result;
}
};
四、总结
等周末补充第三题其他算法