Day2: 双指针+滑动窗口+二分搜索+矩阵

Day2: 双指针+滑动窗口+二分搜索+矩阵

Leetcode 977

Two solotions:

  1. suqare + sort --> O(n+nlogn) = O(nlogn)
class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        for i in range(len(nums)):
            nums[i] = nums[i]**2
        return sorted(nums)
  1. two pointer + reverse --> O(n+n) = O(n)
class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        start = 0
        final = len(nums)-1
        res = []
        while start<=final:
            if nums[start]**2>=nums[final]**2:
                res.append(nums[start]**2)
                start+=1
            else:
                res.append(nums[final]**2)
                final-=1
        return res[::-1]

Leetcode 209

滑动窗口暴力解

        if sum(nums)<s:
            return 0
        res = float("inf")   
        Sum = 0     
        i = 0   
        for j in range(len(nums)):
            Sum += nums[j]
            while Sum >= s:
                res = min(res, j-i+1)
                Sum -= nums[i]
                i += 1
        return res

Leetcode 59

好难!!!!!!
边界条件(offset设定)+循环不变量+起始点定义更新

从哪里开始循环?
循环几个?
什么顺序?
nums[x][y]怎么更新?

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        nums = [[0] * n for _ in range(n)]
        startx, starty = 0, 0               # 起始点
        loop, mid = n // 2, n // 2          # 迭代次数、n为奇数时,矩阵的中心点
        count = 1                           # 计数

        for offset in range(1, loop + 1) :
            for i in range(starty, n-offset): #左闭右开 left>right
                nums[startx][i] = count
                count+=1
            for i in range(startx, n-offset):
                nums[i][n-offset] =count
                count+=1
            for i in range(n-offset, starty, -1):
                nums[n-offset][i] = count 
                count+=1
            for i in range(n-offset, startx, -1):
                nums[i][starty] = count
                count+=1              
            startx += 1    
            starty += 1

        if n % 2 != 0 :			# n为奇数时,填充中心点
            nums[mid][mid] = count 
        return nums

明天继续加油!

总结:数组

这两天复习了python数组 string list matrix;
算法用到了 二分搜索,排序,滑动窗口, 双指针;这都是数组的常见考点!
双指针怎么定义?
滑动窗口怎么开始怎么结束什么条件?
二分搜索定义区间?左闭右开 要统一!
排序算法还没太多,sort() and sorted() in python (O(nlogn))!

你可能感兴趣的:(算法,leetcode,职场和发展,python,经验分享)