977.有序数组的平方
题目:977. 有序数组的平方 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
拿到题目时下意识反应某一指针会用于遍历,思维定式了
因为数组固定长度,遍历计数可以用数组索引,和双指针无关买,27移除元素那一题++用p2指针遍历因为它的移动方式形同索引
从前往后和从后往前遍历都可,所以双指针从中间或者两端出发都可
solution
public class Solution {
public int[] SortedSquares(int[] nums) {
int[] result = new int[nums.Length];
int left = 0;
int right = nums.Length - 1;
for(int i = nums.Length-1; i >= 0; i --)
{
int a = nums[left] * nums[left];
int b = nums[right] * nums[right];
if(a >= b)
{
result[i] = a;
left ++;
}
else
{
result[i] = b;
right --;
}
}
return result;
}
}
summary
错误:从后往前遍历i--。。。
209.长度最小的子数组
题目:209. 长度最小的子数组 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
思想上滑动了,但操作上滑错了
solution
public class Solution {
public int MinSubArrayLen(int target, int[] nums) {
int result = nums.Length + 1;
int sum = 0;
int i = 0;
for(int j = 0; j < nums.Length; j ++)
{
sum += nums[j];
while(sum >= target)
{
sum -= nums[i];
i ++;
result = result < j - i + 2 ? result : j - i + 2;
}
}
return result == nums.Length + 1 ? 0 : result;
}
}
summary
错误:
1、我的错误代码:
public class Solution {
public int MinSubArrayLen(int target, int[] nums) {
int result = nums.Length + 1;
int left = 0;
int right = 0;
int sum = 0;
while(left < nums.Length)
{
sum = sumab(nums, left, right);
if(sum >= target)
{
result = right - left + 1 < result ? right - left + 1 : result;
right += left == right ? 1 : 0;
left ++;
}
else
{
if(right == nums.Length - 1) break;
right ++;
}
}
return result == nums.Length + 1 ? 0 : result;
}
public int sumab(int[] nums, int a, int b)
{
int sum = 0;
while(a <= b)
{
sum += nums[a];
a ++;
}
return sum;
}
}
时间复杂度考虑的是最坏情况
2、出于想要一次性拿到一次循环内最小的result,将result更新写在了while外面。。。
可以将其放进while里,也可以加一个条件判断
for(int j = 0; j < nums.Length; j ++)
{
sum += nums[j];
if(sum >= target)
{
while(sum >= target)
{
sum -= nums[i];
i ++;
}
result = result < j - i + 2 ? result : j - i + 2;
}
}
59.螺旋矩阵II
题目:59. 螺旋矩阵 II - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
做过一遍的题目怎么会完全没有想法啊!
知道正确的遍历方法及注意事项但不会用代码(数学)语言表达;
下次把遍历的索引直接列出来直观找规律。。。
solution
summary
错误:
1、Cannot implicitly convert type 'int[*,*]' to 'int[][]'
int矩阵初始化错误
2、区间开闭
错误代码
while(counter < n * n)
{
for(int i = start; i <= end; i++) result[i][start] = counter ++;
for(int i = start; i <=end; i ++) result[end][i] = counter ++;
for(int i = end; i >= start; i --) result[i][end] = counter ++;
for(int i = end; i >= start; i --) result[start][i] = counter ++;
start ++;
end --;
}
3、转错方向
错误代码
while(counter < n * n)
{
for(int i = start; i < end; i++) result[i][start] = counter ++;
for(int i = start; i < end; i ++) result[end][i] = counter ++;
for(int i = end; i > start; i --) result[i][end] = counter ++;
for(int i = end; i > start; i --) result[start][i] = counter ++;
start ++;
end --;
}
int[i][j]:i表示的是行,j表示的是列
4、中间莫名其妙填了一个0
因为start=end的时候进不了循环最后一格,加条件判定
注意:循环判定
循环判定是counter<=n*n还是counter<n*n
while循环注意检查边界条件——最后一次循环结束时的情况