代码随想录算法训练营第二天 | LeetCode977有序数组的平方、LeetCode209 长度最小的子数组、LeetCode59螺旋矩阵II、数组总结

代码随想录算法训练营第二天 | LeetCode977有序数组的平方、LeetCode209 长度最小的子数组、LeetCode59螺旋矩阵II、数组总结

时长:大约3~4小时

977. Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order .

Example 1:

Example 2:

Constraints:

1 <= nums.length <= 104

-104 <= nums[i] <= 104

nums is sorted in non-decreasing order.

Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?

解题思路:

题意理解:

一个数组从小到大排列,有负数,需要对整个数组平方之后在从小到大排序输出;

双指针:

平方后,最大元素在两头,而不是中间

对于结果的数组,从后往前赋值,两个指针分别指向平方后的数组前后,先把较大的放进结果数组;

需要注意的要点:

要靠了最后两个指针碰头的情况。

209. Minimum Size Subarray Sum

Given an array of positive integers nums and a positive integer target, return *the minimal length of a *

subarray

whose sum is greater than or equal to* target. If there is no such subarray, return 0 instead.

Example 1:

Example 2:

Example 3:

Constraints:

1 <= target <= 109

1 <= nums.length <= 105

1 <= nums[i] <= 104

Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log(n)).

解题思路:

利用曾经学习过的双指针:

right指针

不断往前走,直到区间内的数组和达到要求

left指针

当区间内的元素满足要求时,向前走,缩小数组长度,直到不满足条件

需要注意的要点:

注意对于每个元素是先加上去,然后在做判断是否要更新left指针

59. Spiral Matrix II

Given a positive integer n, generate an n x nmatrix filled with elements from 1 to n2 in spiral order.

Example 1:

代码随想录算法训练营第二天 | LeetCode977有序数组的平方、LeetCode209 长度最小的子数组、LeetCode59螺旋矩阵II、数组总结_第1张图片

Example 2:

Constraints:

1 <= n <= 20

解题思路:

在外面一圈一圈的处理

对于奇数的边长,单独处理中心

每条边的左右边界应当一致,方便代码理解

需要注意的要点:

耐心一些

数组总结

双指针思想

快慢指针

前后指针

区间不变量的控制

声明:

文章中LeetCode的题目来自LeetCode官网:https://leetcode.cn/problems

你可能感兴趣的:(代码随想录,算法,数据结构)