Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >数组矩阵杂题

数组矩阵杂题

原创
作者头像
王脸小
修改于 2020-08-06 03:10:47
修改于 2020-08-06 03:10:47
72600
代码可运行
举报
文章被收录于专栏:王漂亮王漂亮
运行总次数:0
代码可运行

双指针

42. 接雨水

Trapping Rain Water

Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.

The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!

Example:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Solution

暴力法:n方,每个位置求左右最大值

以下方法O(3n),res[i] = min(left_max, right_max),一次性求好左边最大值和右边最大值

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution:
    def trap(self, height) -> int:
        if len(height) <= 2: return 0
        left_max, right_max = [height[0]] + [0]*(len(height)-1), [0]*(len(height)-1) + [height[-1]]
        
        res = 0
        for i in range(1, len(height)):
            left_max[i] = max(left_max[i-1], height[i])
            
        for i in reversed(range(len(height)-1)):
            right_max[i] = max(right_max[i+1], height[i])
            
        for i in range(1, len(height)-1):
            cur = min(left_max[i-1], right_max[i+1]) - height[i]
            res += cur if cur>0 else 0
            
        return res

Solution - 双指针

labuladong的讲解

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution(object):
    def trap(self, height):
        if not height: return 0
        left, right = 0, len(height)-1
        res = 0
        left_max = height[0]
        right_max = height[-1]
        
        while left <= right:
            left_max = max(left_max, height[left])
            right_max = max(right_max, height[right])  
            
            if left_max < right_max:
                res = res + left_max - height[left] 
                left += 1
            else:
                res = res + right_max - height[right] 
                right -= 1            
                
        return res

Follow up是如果不是从天而降的雨水,而是一桶x unit的水,从给定的index往下倒水,最后困住多少水。只讲思路

11. 盛最多水的容器

Container With Most Water

Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: [1,8,6,2,5,4,8,3,7]
Output: 49

Solution

思路(并不是自己想的):Reference,左右双指针,l从前往后,r从后往前,每次移动l和r中较小的值,算当前面积

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution:
    def maxArea(self, height: List[int]) -> int:
        if not height: return 0
        
        res = 0
        l, r = 0, len(height)-1
        while l < r:
            res = max(res, (r-l)*min(height[l],height[r]))
            if height[l] <= height[r]:
                l += 1
            else:
                r -= 1
                
        return res

数组

239. 滑动窗口最大值 - H

Sliding Window Maximum

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Example:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7] 
Explanation: 

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Note: You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.

Follow up: Could you solve it in linear time?

Solution - 暴力

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution:
    def maxSlidingWindow(self, nums, k: int):
        if not nums: return []
        res = []
        
        for end in range(k, len(nums)+1):
            start = end-k
            res += [max(nums[start:end])]
            
        return res

Solution - 单调队列

On时间,Ok空间

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
from collections import deque
class MonotonicQueue:
    def __init__(self):
        self.data = deque()
    
    def push(self, x):
        while self.data and self.data[-1] < x:
            self.data.pop()
        self.data.append(x)
            
    def max(self):
        return self.data[0]
    
    def pop(self, x):
        if self.data and self.data[0] == x:
            self.data.popleft()
    
class Solution(object):
    def maxSlidingWindow(self, nums, k):
        res =[]
        window = MonotonicQueue()
        
        for i in range(len(nums)):
            if i < k-1:
                window.push(nums[i])
            else:
                window.push(nums[i])
                res += [window.max()]
                window.pop(nums[i-k+1])
                
        return res

巨好的单调队列讲解 Python答案

41. 缺失的第一个正数

First Missing Positive

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: [1,2,0]
Output: 3

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: [3,4,-1,1]
Output: 2

Example 3:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution:
    def firstMissingPositive(self, nums) -> int:
        n = len(nums)
        for i in range(n):
            while 1 <= nums[i] <= n and nums[nums[i] - 1] != nums[i]:
                nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
        for i in range(n):
            if nums[i] != i + 1:
                return i + 1
        return n + 1

51.上一个排列

Given a list of integers, which denote a permutation.

Find the previous permutation in ascending order.

The list may contains duplicate integers.

Example 1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input:[1]
Output:[1]

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input:[1,3,2,3]
Output:[1,2,3,3]

Example 3:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input:[1,2,3,4]
Output:[4,3,2,1]

Solution

从后往前找顺序的第一个i,然后找i后面比i小的最大值j,swap(i,j), reverse[i+1:]

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution:
    def previousPermuation(self, nums):
        if len(nums) <= 1: return nums
        i = len(nums) - 1
        while i > 0 and nums[i] >= nums[i - 1]:
            i -= 1
            
        if i == 0: return nums[::-1]
        
        j = len(nums) - 1
        while nums[j] >= nums[i - 1]:
            j -= 1
        
        nums[i-1], nums[j] = nums[j], nums[i-1]
        
        return nums[:i] + list(reversed(nums[i:]))

重新写吧朋友, Reference

Follow up: 下一个排列

238. 除自身之外的乘积

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

powcai

思路:遍历一遍算i位左边乘积,遍历一遍算i位右边乘积

矩阵

48. 旋转图像 - M

Rotate Image

You are given an n x n 2D matrix representing an image.

Rotate the image by 90 degrees (clockwise).

Note:

You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Given input matrix = 
[
  [1,2,3],
  [4,5,6],
  [7,8,9]
],

rotate the input matrix in-place such that it becomes:
[
  [7,4,1],
  [8,5,2],
  [9,6,3]
]

Example 2:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Given input matrix =
[
  [ 5, 1, 9,11],
  [ 2, 4, 8,10],
  [13, 3, 6, 7],
  [15,14,12,16]
], 

rotate the input matrix in-place such that it becomes:
[
  [15,13, 2, 5],
  [14, 3, 4, 1],
  [12, 6, 8, 9],
  [16, 7,10,11]
]

Solution

powcai

找规律直接计算对应位置

54. 螺旋矩阵 - M

Spiral Matrix

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input:
[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

Solution

两种解法-powcai

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        if not matrix: return []
        top, bottom = 0, len(matrix) - 1
        left, right = 0, len(matrix[0]) - 1
        
        res = []
        while top <= bottom and left <= right:
            #从左到右
            for i in range(left, right+1):
                res.append(matrix[top][i])
            top += 1
            if top > bottom: break
            #从上到下
            for i in range(top, bottom+1):
                res.append(matrix[i][right])
            right -= 1
            if left > right: break
            #从右到左
            for i in range(right, left-1, -1):
                res.append(matrix[bottom][i])
            bottom -= 1
            #从下到上
            for i in range(bottom, top-1, -1):
                res.append(matrix[i][left])
            left += 1
            
        return res

思路:寻常思路,一直逆时针旋转

304. 2D区域和检索(不可变)

Range Sum Query 2D - Immutable

Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).

Example:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Given matrix = [
  [3, 0, 1, 4, 2],
  [5, 6, 3, 2, 1],
  [1, 2, 0, 1, 5],
  [4, 1, 0, 1, 7],
  [1, 0, 3, 0, 5]
]

sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12

Note: You may assume that row1 ≤ row2 and col1 ≤ col2.

powcai, init里面一次性求好ij位置左上方的sum

等于黄色的部分总和 - 两个橙色总和 + 红色部分 ( 因为我们发现当我们减去橙色部分, 红色部分多删除一次)

Math

204. 计算质数

Count Primes

Count the number of prime numbers less than a non-negative number, n.

Example:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.

Solution

ladong, Onloglogn

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Solution(object):
    def countPrimes(self, n):
        if n<=2: return 0
        isPrime = [True]*(n)
        for i in range(2, int(n**0.5)+1):
            if isPrime[i]:
                # i 的倍数不可能是素数
                for j in range(2*i, n, j + i):
                    isPrime[j] = False
        
        cnt=0
        for p in isPrime:
            if p: cnt+=1
                
        return cnt-2

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
【愚公系列】2023年11月 大数据教学课程 003-Linux权限和系统相关命令
Linux权限指的是文件或目录在系统中的访问权限,分为读、写、执行三种权限,通过权限设置可以保护系统的安全性。
愚公搬代码
2025/06/02
900
【愚公系列】2023年11月 大数据教学课程 003-Linux权限和系统相关命令
100 条 Linux vim 命令备忘单,收藏起来随时备用!
前两天给大家带来了Linux常用的命令,有小伙伴想要vim相关命令备忘单,那么今天瑞哥安排。
网络技术联盟站
2023/03/05
1.7K0
100 条 Linux vim 命令备忘单,收藏起来随时备用!
学会这21条,你离Vim大神就不远了
导语:作者本人是 Vim 的重度使用者,就因为喜欢上这种双手不离键盘就可以操控一切的feel,Vim 可以让人对文本的操作更加精准、高效。对于未使用过 Vim 的朋友来说,可能还无法体会到这种感觉。由于使用 Vim 有一定的学习成本,只有做到非常熟练的程度才能感受到它带来的快捷。
AI科技大本营
2019/08/20
1.9K0
学会这21条,你离Vim大神就不远了
一定要知道的,那些Linux操作命令(二)
王豆豆最近换了份工作,今天去医院做入职体检,所以更新就晚了些。 目录 1.文件和目录操作命令 2.用户和用户组操作命令 3.vim编辑器操作命令 4.打包和解压操作命令 5.系统操作命令 //用户与用户组操作命令 useradd 创建用户 1.不指定任何信息,创建一个用户 [root@localhost network-scripts]# useradd test_dir 修改的文件 (1)passwd文件: test_dir:x:502:502::/home/test_dir:/bin/bash
王豆豆
2018/06/08
8130
Linux入门篇 —— 超实用 Linux 常用命令
- 选项: - -w: 统计字数 一个字被定义为由空白,跳格(制表符),换行以这些为分割字符串 - -l: 行数 - -c: 字节数 - -m: 字符数 -m -c不能一起使用 - -L: 打印最长行的长度
ruochen
2021/02/01
8800
Linux入门篇 —— 超实用 Linux 常用命令
Linux基础Day02
在没有图形界面的环境下, 要编辑文件, vi是最佳选择 每一个使用linux的程序员,都应该或多或少的学习一些vi的常用命令
Maynor
2021/04/09
6520
日常记录(2)vim操作查询手册
退出vim 按键 功能 :wq 保存退出 :w filename 保存到指定文件 :q 退出,如果文件修改但没有保存,会提示无法退出 :q! 退出,不保存 进入插入模式 按键 功能 a 光标位置右边插入文字 i 光标位置当前处插入文字 o 光标位置下方开启新行 O 光标位置上方开启新行 I 光标所在行首插入文字 A 光标所在行尾插入文字 进入可视化模式 按键 功能 Ctrl+v 进入可视化编辑模式 其它 按键 功能 :set expandtab tab展开为空格 cc/S 清除整行,进入插入模式 d$
嘘、小点声
2021/12/07
1K0
打造专属于你自己的vim
转载自:https://segmentfault.com/a/1190000011466454  作者:SF / 枫上雾棋
用户1634449
2018/09/21
6610
打造专属于你自己的vim
vim的快捷键大全
vim中Nyy可以复制光标后的N行。有时我们不容易得出行数,这时可以用做标记的方法来制定复制范围:
王小雷
2019/05/26
2.3K0
生信入门必须掌握的 30 个 Linux 命令
修改工作目录,cd 和 ls 应该是使用最多的两个命令,尤其是对于 Linux 目录结构不熟的用户。
章鱼猫先生
2021/10/15
2.8K1
Linux日常使用技巧
创建软连l接 ln -s {实际文件} {软连接文件} # 软连接指向位置地址。
rolling king
2022/09/07
9990
Linux日常使用技巧
Linux系统之常用命令
环境:CentOS7X64(CentOS Linux release 7.5.1804)
尜尜人物
2020/01/15
1.5K0
Linux系统之常用命令
Vim编辑器基础入门
Vim(Visual Interface|可视化接口),在linux中常常使用的工具,是进行Linux嵌入式编程的必备工具之一; vim最大的贡献就是它的按键系统这也是为什么chrome、idea、atom等编辑器都会提供一个vim mode;
全栈工程师修炼指南
2020/10/23
1.9K0
Vim编辑器基础入门
vim 回顾
下面是一篇旧文,大多是一些已有知识的整理,并不太成熟。欢迎关注专栏 space-vim , 有空我会以 Vim 自带的 help (不妨 :help help 看一下) 为线索, 分享一些关于 Vim 的小知识 ,也会顺带着介绍一下 space-vim 的配置与用法。
用户1558438
2018/08/23
6480
教程 | Vim 教程【命令-操作-快捷键】
来源:http://www.cnblogs.com/softwaretesting/archive/2011/07/12/2104435.html
昱良
2018/12/28
7200
【Linux】Linux常用操作命令(四)
在没有图形界面的环境下, 要编辑文件, vi是最佳选择 每一个使用linux的程序员,都应该或多或少的学习一些vi的常用命令
陶然同学
2023/02/27
1.2K0
【Linux】Linux常用操作命令(四)
Linux vi/vim 中的一些技巧
1. 常用命令 编辑 以下命令在命令模式执行 i,a,r:在光标的前,后,上方插入字符命令(i=insert,a=append,r=replace) O,o:在当前行前面,后面插入一空行 cw,dw:改变(置换)/删除光标所在处的单词的命令 (c=change,d=delete) x,d$,dd:删除光标处,光标之后,光标所在行的字符 光标移动 k,j,h,l:分别上下左右移动光标 Ctrl+f,Ctrl+b:分别向下,向上翻页 n:敲数字然后回车,光标往后移动 n 行 nG:使得光标跳动到指定行 w,
杰哥的IT之旅
2021/06/01
1.1K0
Linux大人养成计划1---基础命令总结
刷了一波视频,现在把Linux的一些常用基本命令总结了下。学会这些,Linux的基本操作就会了。
帅地
2018/08/30
6480
Linux大人养成计划1---基础命令总结
红帽认证RedHat-RHCSA shell的基本应用
Linux命令的通用命令格式:命令字 [选项] [参数] 选项及参数的含义 选项:用于调节命令的具体功能 以 “-”引导短格式选项(单个字符),例如“-l” 以“--”引导长格式选项(多个字符),例如“--color” 多个短格式选项可以写在一起,只用一个“-”引导,例如“-al” 参数:命令操作的对象,如文件、目录名等
青灯古酒
2023/10/16
2270
红帽认证RedHat-RHCSA shell的基本应用
vim基本命令
最实用的几个: 0(数字0)移动到本行第一个字符上  移动到行尾 。 3 移动到下面3行的行尾 gg 移动到文件头。 =  [[ G(shift + g) 移动到文件尾。 =  ]] /text  查
不吃西红柿
2022/07/29
1.5K0
相关推荐
【愚公系列】2023年11月 大数据教学课程 003-Linux权限和系统相关命令
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验