LeetCode977 有序数组的平方和
题目描述:
给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]
示例 2:
输入:nums = [-7,-3,2,3,11]
输出:[4,9,9,49,121]
思路:
(1) 暴力,很简单,用库函数直接排序,开始没想到双指针要怎么解决
(2)双指针,头尾指针,分别向中间遍历,比较每个元素平方和的大小,声明一个数组result[],将最大的平方和元素存到新数组末尾,当满足条件fitst<=last时跳出循环,返回新数组。
代码:
暴力:
public class Solution {
public int[] SortedSquares(int[] nums) {
int[] result = new int[nums.Length];
for (int i = 0; i < nums.Length; i++)
{
result[i] = nums[i] * nums[i];
}
Array.Sort(result);
return result;
}
}
public class Solution {
public int[] SortedSquares(int[] nums) {
int first = 0;
int last = nums.Length - 1;
int[] result = new int[nums.Length];
int k = nums.Length - 1;
while (first <= last)
{
if (nums[first] * nums[first] < nums[last] * nums[last])
{
result[k--] = nums[last] * nums[last];
last--;
}
else
{
result[k--] = nums[first] * nums[first];
first++;
}
}
return result;
}
}
LeetCode209 长度最小的子数组
题目描述:
给定一个含有 n 个正整数的数组和一个正整数 target 。
找出该数组中满足其和 ≥ target 的长度最小的 连续子数组 [numsl, numsl+1, …, numsr-1, numsr] ,并返回其长度。如果不存在符合条件的子数组,返回 0 。
示例 1:
输入:target = 7, nums = [2,3,1,2,4,3]
输出:2
解释:子数组 [4,3] 是该条件下的长度最小的子数组。
示例 2:
输入:target = 4, nums = [1,4,4]
输出:1
示例 3:
输入:target = 11, nums = [1,1,1,1,1,1,1,1]
输出:0
思路:
滑动窗口,双指针的一种变形。
所谓滑动窗口,就是不断的调节子序列的起始位置和终止位置,从而得出我们要想的结果。
使用滑动窗口解题要想明白三个问题:
窗口内是什么?
如何移动窗口的起始位置?
如何移动窗口的结束位置?
代码:
暴力双循环(超时)
public class Solution {
public int MinSubArrayLen(int target, int[] nums) {
int sum = 0;
int len = 0;
int result = int.MaxValue;
for (int i = 0; i < nums.Length; i++)
{
sum = 0;
for (int j = i; j < nums.Length; j++)
{
sum += nums[i];
if (sum >= target)
{
len = j - i + 1;
result = result < len ? result : len;
break;
}
}
}
return result == int.MaxValue ? 0 : result;
}
}
滑动窗口(O(n)):
public class Solution {
public int MinSubArrayLen(int target, int[] nums) {
int result = int.MaxValue;
int sum = 0; // 滑动窗口数值之和
int len = 0; // 滑动窗口的长度
int i = 0; // 滑动窗口起始位置
for (int j = 0; j < nums.Length; j++)
{
sum += nums[j];
while (sum >= target)
{
len = j - i + 1; // 取子序列的长度
result = result < len ? result : len;
sum -= nums[i++]; // 这里体现出滑动窗口的精髓之处,不断变更i(子序列的起始位置)
}
}
return result == int.MaxValue ? 0 : result;
}
}
LeetCode59 螺旋矩阵
题目描述:
给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。
思路:
二分法,循环遍历
代码:
public class Solution {
public int[][] GenerateMatrix(int n) {
int[][] answer = new int[n][];
for (int i = 0; i < n; i++)
answer[i] = new int[n];
int start = 0;
int end = n - 1;
int tmp = 1;
while (tmp < n * n)
{
for (int i = start; i < end; i++) answer[start][i] = tmp++;
for (int i = start; i < end; i++) answer[i][end] = tmp++;
for (int i = end; i > start; i--) answer[end][i] = tmp++;
for (int i = end; i > start; i--) answer[i][start] = tmp++;
start++;
end--;
}
if (n % 2 == 1) answer[n / 2][n / 2] = tmp;
return answer;
}
}
总结:
滑动窗口和螺旋矩阵很难想到怎么解,需要反复多加练习