代码随想录算法训练营第二天 | 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:

<span>1 <= nums.length <= </span>10<sup>4</sup>

-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup>

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 <= 10<sup>9</sup>

1 <= nums.length <= 10<sup>5</sup>

1 <= nums[i] <= 10<sup>4</sup>

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 n<sup>2</sup> in spiral order.

Example 1:

Example 2:

Constraints:

1 <= n <= 20

解题思路:

在外面一圈一圈的处理

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

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

需要注意的要点:

耐心一些

数组总结

双指针思想

快慢指针

前后指针

区间不变量的控制

声明:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值