目录
原题链接:977. 有序数组的平方 - 力扣(LeetCode)
原题链接:209. 长度最小的子数组 - 力扣(LeetCode)
原题链接:59. 螺旋矩阵 II - 力扣(LeetCode)
LeetCode977 :有序数组的平方
题目描述:
给你一个按 非递减顺序 排序的整数数组 nums
,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
解题思路:
暴力:直接平方 之后进行排序
双指针:一个指针指向第一个元素,另一个指针指向最后一个元素 ,将平方后更大的结果,倒序填入结果数组中。
1.双指针解法:
比较两个 指针的值平方后的大小 ,将更大的结果填入结果数组,将指针移动一位
public class Solution
{
public int[] SortedSquares(int[] nums)
{
int[] result = new int[nums.Length];
int left = 0;
int right = nums.Length - 1;
int index = nums.Length - 1;
for (; index >= 0; index--)
{
if (nums[left] * nums[left] > nums[right] * nums[right])
{
result[index] = nums[left] * nums[left];
left++;
}
else
{
result[index] = nums[right] * nums[right];
right--;
}
}
return result;
}
}
原题链接:977. 有序数组的平方 - 力扣(LeetCode)
LeetCode209:长度最小的子数组
题目描述:
给定一个含有 n
个正整数的数组和一个正整数 target
。
找出该数组中满足其总和大于等于 target
的长度最小的 连续子数组 [numsl, numsl+1, ..., numsr-1, numsr]
,并返回其长度。如果不存在符合条件的子数组,返回 0
。
解题思路:
双指针(滑动窗口):一次for循环 来表示滑动窗口的终止位置,其终止位置在和大于目标值时向前移动
1.双指针(滑动窗口):
public class Solution
{
public int MinSubArrayLen(int target, int[] nums)
{
int ans = int.MaxValue;
int slow = 0;
int sum = 0;
int length = 0;
for (int fast = 0; fast < nums.Length; fast++)
{
sum += nums[fast];
while (sum >=target)
{
length = fast - slow + 1;
ans = Math.Min(ans, length);
sum -= nums[slow];
slow ++;
}
}
if (ans == int.MaxValue)//如果ans 没有被赋值 则表示没有符合条件的子数组
{
return 0;
}
else
{
return ans;
}
}
}
原题链接:209. 长度最小的子数组 - 力扣(LeetCode)
LeetCode59:螺旋矩阵II
题目描述:
解题思路:
1.模拟过程: 注意 循环不变量原则。坚持左闭右开 模拟过程
1.模拟过程:
public class Solution
{
public int[][] GenerateMatrix(int n)
{
int[][] ans = new int[n][];
for (int i = 0; i < n; i++)
{
ans[i] = new int[n];
}
int value = 1;
int start = 0;
int end = n - 1;
while (value<n*n)
{
for (int j = start; j < end; j++)
{
ans[start][j] = value++;
}
for (int i = start; i < end; i++)
{
ans[i][end] = value++;
}
for (int j = end; j >start; j--)
{
ans[end][j]=value++;
}
for (int i =end; i >start; i--)
{
ans[i][start] = value++;
}
start++;
end--;
}
if(n%2==1)//如果是奇数 要填入中间的值
{
ans[n / 2][n / 2] = value;
}
return ans;
}
}