977、有序数组的平方
1)暴力解法
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
new_nums = sorted(nums, key=lambda x: abs(x), reverse=False)
return [i*i for i in new_nums]
# runtime:40 ms
# memory:14.8 MB
采用库函数使用方便,sorted方法的时间复杂度为O(nlogn),还有更简洁的一行代码:
return sorted(i**2 for i in nums)
2)双指针解法
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums = [i**2 for i in nums]
left, right, index = 0, len(nums) - 1, len(nums) - 1
res = [0] * len(nums)
while left <= right:
if nums[left] <= nums[right]:
res[index] = nums[right]
right -= 1
elif nums[left] > nums[right]:
res[index] = nums[left]
left += 1
index -= 1
return res
# runtime:36 ms
# memory:14.8 MB
双指针用在此处前提是nums已排好序,平方后负数变为正,最大的必然出现在两端,因此考虑对向双指针;
209、长度最小的子数组
class Solution(object):
def minSubArrayLen(self, target, nums):
"""
:type target: int
:type nums: List[int]
:rtype: int
"""
left, right = 0, 0
len_window = len(nums)+1
sum_num = 0
while len(nums) > right >= left:
if sum_num < target:
sum_num += nums[right]
while sum_num >= target:
len_window = min(len_window, (right-left+1))
sum_num -= nums[left]
left += 1
right += 1
return len_window if len_window <= len(nums) else 0
# runtime:36 ms
# memory:19.7 MB
采用滑动窗口方法能很好解决本题,第一次做的时候思路是想对了,不过代码处理慢指针移动的的时候条件判断处理的不对,导致一直在最后几个用例的地方报错,if改成while后才AC
59、螺旋矩阵II
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
nums = [[0]*n for _ in range(n)]
x, y = 0, 0
loop = n // 2
offset = 1
cnt = 1
while loop:
global i, j
for j in range(x, n-offset):
nums[x][j] = cnt
cnt += 1
for i in range(y, n-offset):
nums[i][n-offset] = cnt
cnt += 1
for j in range(n-offset, x, -1):
nums[n-offset][j] = cnt
cnt += 1
for i in range(n-offset, y, -1):
nums[i][y] = cnt
cnt += 1
x += 1
y += 1
offset += 1
loop -= 1
if n % 2 == 1:
nums[n//2][n//2] = cnt
return nums
# runtime:16 ms
# memory:13 MB
关键是需要确定好循环条件->即循环次数,边界值->即每条边遍历的时候不动的那个数值一定要写对,如果是左闭右开区间,遍历下一条边的时候要取上一条边未包括进来的那个值
数组专题总结:
1、数组是一组内存地址连续的相同类型数据的集合,其中元素的查询是O(1)的,插入和删除是O(n)的,二维数组的地址是不连续的;
2、针对数组的操作方法有二分法、双指针、滑动窗口、模拟等方法。