LeetCode (1) | 数组

本文精选LeetCode经典算法题目,涵盖两数之和、杨辉三角、求众数等,解析高效算法思想,如双指针、动态规划等,助力提升算法能力。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个参考博客

一、Easy

(1)两数之和 II - 输入有序数组

给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

你可以假设每个输入都只有一个解决方案,而且你不会重复使用相同的元素。

输入:数组 = {2, 7, 11, 15}, 目标数 = 9
输出:index1 = 1, index2 = 2


错误想法:试图找到target/2在数组中的位置,再往两边查找

正确想法:从头尾开始查找,计算头尾相加与target的大小关系


(2)杨辉三角

注意从后往前做相加计算,否则会覆盖前面数字,导致计算出现问题


(3)二维数组查找

在一个从左往右,从上往下递增的二维数组中查找指定的数

分治法思想:

        以右上角为起点,一次减去一行或者一列,时间复杂度O(n)

        对边界情况的考虑,增加鲁棒性

二分法思想:

        先通过行的二分,实现了对二维矩阵的二分法,再进行列的二分


(4)求众数

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。

你可以假设数组是非空的,并且数组中的众数永远存在。

想法:使用count计数,碰到该数+1,否则-1,为0时更新存储的数


(5)移动零

给定一个数组 nums, 编写一个函数将所有 0 移动到它的末尾,同时保持非零元素的相对顺序。

例如, 定义 nums = [0, 1, 0, 3, 12],调用函数之后, nums 应为 [1, 3, 12, 0, 0]

我的想法:

        用后面的数字直接去覆盖掉前面的0,使用count计0出现数,而后碰到的非零数均向前count

更好的想法:

        每次记录第一个零的位置,与后面出现的数字做交换


(6)买卖股票的最佳时机

假设你有一个数组,其中第 i 个元素是一支给定股票第 i 天的价格。

如果您只能完成最多一笔交易(即买入和卖出一股股票),则设计一个算法来找到最大的利润。

示例 1:

输入: [7, 1, 5, 3, 6, 4]
输出: 5

最大利润 = 6-1 = 5(不是 7-1 = 6, 因为卖出价格需要大于买入价格)

示例 2:

输入: [7, 6, 4, 3, 1]
输出: 0

在这种情况下, 没有交易完成, 即最大利润为 0。
一个想法:3,5,1,4,即从前往后碰到更小的数,则去计算更小数的profit与之前profit的比较


(7) 旋转数组

将包含 n 个元素的数组向右旋转 步。

例如,如果  n = 7 ,  k = 3,给定数组  [1,2,3,4,5,6,7]  ,向右旋转后的结果为 [5,6,7,1,2,3,4]

想法:

如果允许额外分配线性空间,那么可以错位复制原有数组的元素。如果允许修改原有数组,那么可以通过三次反转

数组来实现收旋转,不需要申请额外空间,并且每次反转时间为O(n),

三次反转数组:第一次反转整个数组;第二次反转数组的前K个数;第三次反转数组剩下的数

例如:

一维数组[1,2,3,4,5,6,7],k=3

第一次反转:7,6,5,4,3,2,1

第二次反转:5,6,7,4,3,2,1

第三次反转:5,6,7,1,2,3,4    最终结果


(8)最长公共前缀

编写一个函数来查找字符串数组中最长的公共前缀字符串。

想法:注意数组越界,使用第一个str作为基准,首先要比较后续str与选定的公共字符串的大小,超过说明该公共字符串不可能是真的公共的


(9)最大子序和

给定一个序列(至少含有 1 个数),从该序列中寻找一个连续的子序列,使得子序列的和最大。

例如,给定序列 [-2,1,-3,4,-1,2,1,-5,4]
连续子序列 [4,-1,2,1] 的和最大,为 6

思路:

当从头遍历数组元素时,对于数组中的一个整数有几种选择呢? 

两种:加入之前的subArray;自己另起一个新的subArray.那么时候会出现这两种状况: 
- 当之前subArray 的总和大于 0 时,我们认为 其对后续结果是有贡献的,这种情况下,我们选择加入之前的subArray 
- 当之前subArray 的总和小于等于0时,我们认为其对后续结果是没有贡献的,这种情况下,我们选择以当前数字开始,另起一个subArray

定义两个变量maxsum和curSum,其中maxsum保存最终要返回的结果,即最大的子数组之和,curSum初始值为nums[0],每遍历一个数字num,比较curSum + num和num中的较大值存入curSum,然后再把maxsum和curSum中的较大值存入maxsum,以此类推直到遍历完整个数组,可得到最大子数组的值存在maxsum中。


(10)找到所有数组中消失的数字

给定一个范围在  1 ≤ a[i] ≤ n ( n = 数组大小 ) 的 整型数组,数组中的元素一些出现了两次,另一些只出现一次。

找到所有在 [1, n] 范围之间没有出现在数组中的数字。

您能在不使用额外空间且时间复杂度为O(n)的情况下完成这个任务吗? 你可以假定返回的数组不算在额外空间内。

示例:

输入:
[4,3,2,7,8,2,3,1]

输出:
[5,6]

这类问题的一个重要条件就是1 ≤ a[i] ≤ n (n = size of array),不然很难在O(1)空间和O(n)时间内完成。

第一种解法,这种解法的思路路是,对于每个数字nums[i],如果其对应的nums[nums[i] - 1]是正数,我们就赋值为其相反数,如果已经是负数了,就不变了

第一次遍历:用相反数的形式标记出现过的数字(下标);

第二次遍历:找出没有被标记的数字(下标),并返回;


(11)Contains Duplicate

Given an array of integers, find if the array contains any duplicates.

Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

Example 1:

Input: [1,2,3,1]
Output: true

Example 2:

Input: [1,2,3,4]
Output: false

思路:判断是否在字典中,在则重复,否则新增键值


(12)Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

想法:

(1)每个数往前找1-k,判断有无相等,但是这种方法速度慢

(2)其他人的想法:用字典存储数字及其对应下标,加快速度,每次从字典中搜索


(13)Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

思路:这道题如果直接暴力的在k个窗口里进行比较计算,时间会超时。参考了网上的答案,使用桶排序。

如果: | nums[i] - nums[j] | <= t   式a

等价: | nums[i] / t - nums[j] / t | <= 1   式b

推出: | floor(nums[i] / t) - floor(nums[j] / t) | <= 1   式c

​等价: floor(nums[j] / t) ∈ {floor(nums[i] / t) - 1, floor(nums[i] / t), floor(nums[i] / t) + 1} 式d

上面的除法均为整除(floor地板除),通过除法减少了需要查找的数目,只需要查找数目,key = nums[i]/max(1,t),则只需查找key,key-1,key+1是否出现在k的

窗口内即可。通过orderedDict维护一个滑动窗口为k的字典,(orderedDict按照插入字典的顺序排序,也可以设置按照key或者value排序,此处使用插入顺序

排序即可)字典key为k窗口内的nums[i]/t,而value为他们的原始值。

心得:凡是涉及到间隔、距离的,都有可能应用桶排序


二、middle

(1)3sum

Given an array nums of n integers, are there elements abc in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

The solution set must not contain duplicate triplets.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

参考:https://blog.youkuaiyun.com/haolexiao/article/details/70768526

最初想法,将数分成正数负数,然后取一正二负,或者二正一负,这样时间复杂度太高了

正确做法:基于2sum,排序后先选出一个数,然后剩下两个从左右两边逼近求和,这样复杂度为O(n2),这里要注意的是重复问题,注意检查


(2)3Sum Closest

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.

The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).


我的思路:左右滑动时想通过一个从>target到<target的变化,来减少搜索次数,后来发现这个其实很复杂而且并没有什么卵用


正确思路:定义一个变量diff用来记录差的绝对值,然后我们还是要先将数组排个序,然后开始遍历数组,思路跟那道三数之和很相似,都是先确定一个数,然后

用两个指针left和right来滑动寻找另外两个数,每确定两个数,我们求出此三数之和,然后算和给定值的差的绝对值存在newDiff中,然后和diff比较并更

新diff和结果closest即可


(4)4sum (ksum)

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

我的想法:固定第一个,第二个数,然后使用2sum做,这个ksum系列要注意的就是不重复,使用的诀窍是:

对于四个变量,每个都要做个检查

if i > 0 and nums[i] == nums[i-1]
if j > i+1 and nums[j] == nums[j-1]
if l > j+1 and nums[l] == nums[l-1]

if r < len(nums)-1 and nums[r] == nums[r+1]

上述可以实现,但较为麻烦,别人的想法: 递归调用ksum,直到为2sum(见代码)


(5) next permutation(生成字典序)


Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place and use only constant extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

看具体例子,一个排列为124653,如何找到它的下一个排列,因为下一个排列一定与124653有尽可能长的前缀,从后往前找

124653,显然最后1个数字3不具有下一个全排列。

第二步:找最后面2个数字的下一个全排列。

124653,显然最后2个数字53不具有下一个全排列。

第三步:找最后面3个数字的下一个全排列。

124653,显然最后3个数字653不具有下一个全排列。

------到这里相信大家已经看出来,如果一个序列是递减的,那么它不具有下一个排列

第四步:找最后面4个数字的下一个全排列。

124653,我们发现显然最后4个数字4653具有下一个全排列。因为它不是递减的,例如6453,5643这些排列都在4653的后面。

124653的下一个为125346: 找到4<6,序列非递减以后,一次循环,从4后面的序列中找到大于4最接近4的数(不一定是5,因为5可能在4前面),与4交换位置,得到序列125643,而后再一个循环,将该位置后面的低减排列改为递增排列,即变为125346


(6)Permutation Sequence

The set [1,2,3,...,n] contains a total of n! unique permutations.

By listing and labeling all of the permutations in order, we get the following sequence for n = 3:

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.

Note:

  • Given n will be between 1 and 9 inclusive.
  • Given k will be between 1 and n! inclusive.
思路:

当n = 4时,其排列组合共有4! = 24种,我们就以n = 4, k = 17的情况来分析,所有排列组合情况如下:

1234
1243
1324
1342
1423
1432
2134
2143
2314 
2341
2413
2431
3124
3142
3214
3241
3412 <--- k = 17
3421
4123
4132
4213
4231
4312
4321

我们可以发现,每一位上1,2,3,4分别都出现了6次(即3!),当第一位上的数字确定了,后面三位上每个数字都出现了2次(2!),当第二位也确定了,后面的数字都只出现了1次(1!),当第三位确定了,那么第四位上的数字也只能出现一次,那么下面我们来看k = 17这种情况的每位数字如何确定,由于k = 17是转化为数组下标为16

最高位可取1,2,3,4中的一个,每个数字出现3!= 6次,所以k = 16的第一位数字的下标为16 / 6 = 2,即3被取出
第二位: 此时的k' = 16 % (3!) = 4,而剩下的每个数字出现2!= 2次,所以第二数字的下标为4 / 2 = 2,即4被取出
第三位: 此时的k'' = 4 % (2!) = 0,而剩下的每个数字出现1!= 1次,所以第三个数字的下标为 0 / 1 = 0,即1被取出
第四位: 此时的k''' = 0 % (1!) = 0,而剩下的每个数字出现0!= 1次,所以第四个数字的下标为0 / 1= 0,即2被取出

那么我们就可以找出规律了
a1 = k / (n - 1)!
k1 = k

a2 = k1 / (n - 2)!
k2 = k1 % (n - 2)!
...

an-1 = kn-2 / 1!
kn-1 = kn-2 / 1!

an = kn-1 / 0!
kn = kn-1 % 0!


(7)Remove Duplicates from Sorted Array II

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example :

Given nums = [0,0,1,1,1,1,2,3,3],

Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively.

It doesn't matter what values are set beyond the returned length.

解法(网上):    

        i = 2
        index = 2      
        for i in range(2,len(nums)):
            #与index-2去比较,即会与之前保存的上一个数字进行比较,只有不同才会被留下
            if nums[i] != nums[index-2]:
                nums[index] = nums[i]
                index += 1
        return index


(8)Valid Sudoku

参考博客


(9) 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:

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]
]

思路:

1    2   3   4

5    6   7   8

9   10 11 12

13 14 15 16

第一步,沿着对角线置换([i][j] 和 [j][i]):

1    5   9   13

2    6  10   14

3    7  11   15

4   8   12   16

第二步,逆置每行


(10)Climbing Stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

Example:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

思路:使用递归超时,故此处使用动态规划,f(n)=f(n-1)+f(n-2)


(11)Set Matrix Zeroes

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Example 1:

Input: 
[
  [1,1,1],
  [1,0,1],
  [1,1,1]
]
Output: 
[
  [1,0,1],
  [0,0,0],
  [1,0,1]
]
思路:
使用额外的空间的话,就是做两个一维数组,分别标记哪一行哪一列有0,然后把这些行和列都清0即可。这样空间复杂度为O(m+n);
不使用额外空间的方法类似,就是把第一行和第一列作为标记。  首先  先判断第一行第一列是否含有0,并用两个bool变量记录起来。
其次,遍历其他行和列,如果有0,就把该元素所在的行和列  分别记录起来,即把第一列的该行置0,把第一行的该列置为0;比如  matrix[1][2]==0,
那么,把matrix[i][0]和matrix[0][j]都置零。


(12)Gas Station

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

Note:

  • If there exists a solution, it is guaranteed to be unique.
  • Both input arrays are non-empty and have the same length.
  • Each element in the input arrays is a non-negative integer.

Example 1:

Input: 
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

Output: 3
我的思路:每次都累加判断,则时间复杂度为O(n*n),其实只需一次遍历即可(O(n)),使用上一次遍历的和去计算下一次的
更快的思路:gas求和必须大于cost,然后对于每个点一旦求和小于零就置为0,继续向后求和(不需要计算前面部分的和,因为已经gas求和大于cost)(见代码)


(13)Game of Life

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input: 
[
  [0,1,0],
  [0,0,1],
  [1,1,1],
  [0,0,0]
]
Output: 
[
  [0,0,0],
  [1,0,1],
  [0,1,1],
  [0,1,0]
]

Follow up:

  1. Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
  2. In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?


思路:这道题本身不难,原地进行更新,即使用编码去表示1到0,0到1的转变,可以使用2,3去更新,而后对2取模,可以还原。比较难的是后面的问题,具体可以参考[Leetcode] Game of Life 生命游戏



(12)Increasing Triplet Subsequence

Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.

Formally the function should:

Return true if there exists  i, j, k 
such that  arr[i] <  arr[j] <  arr[k] given 0 ≤  i <  j <  k ≤  n-1 else return false.

Your algorithm should run in O(n) time complexity and O(1) space complexity.

Examples:
Given [1, 2, 3, 4, 5],
return true.

Given [5, 4, 3, 2, 1],
return false.

思路:使用max和min分别保存递增的两个数,而后碰到大于min小于max的则更新max,小于min的则更新min,大于max即表示True,更加简洁的写法如下

        n1 = n2 = float('inf')
        for n in nums:
            if n <= n1:
                n1 = n
            elif n <= n2:
                n2 = n
            else:
                return True
        return False
还可以参考: 点击打开链接



三、hard

(1)Longest Consecutive Sequence

Given an unsorted array of integers, find the length of the longest consecutive elements sequence.

Your algorithm should run in O(n) complexity.

Example:

Input: [100, 4, 200, 1, 3, 2]
Output: 4
Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4.
Solution: 使用字典作为hash_map,初始字典值都为false,对于其中每个数,判断其是否为false,是,则检查其左右两边的连续的数是否在字典内,在则继续检查,使用leftlen和rightlen去记录左右两边长度,与maxlen比较更新


(2)两个排序数组的中位数

有两个大小为 m 和 n 的排序数组 nums1 和 nums2 

请找出两个排序数组的中位数并且总的运行时间复杂度为 O(log (m+n)) 。

参考:https://github.com/yuzhangcmu/LeetCode/blob/master/array/FindMedianSortedArrays.java

1. 我们借用findKthNumber的思想。先实现findKthNumber,如果是偶数个,则把中间2个加起来平均,奇数就用中间的。

2. 为了达到LOG级的复杂度,我们可以这样:

每次在A,B取前k/2个元素。有以下这些情况:

1). A的元素个数 < k/2,则必有k/2个在B内,所以可以丢弃Bk/2. 反之亦然。

证明:

我们使用反证法。

假设第K大在B的前k/2中,例如位置在索引m(m<= k/2-1)那么A必然拥有前k中的k -(m+1)个元素,而

m <= k/2-1,则 m+1 <=k/2  , k - (m+1) >= k/2与条件:A的元素不够k/2矛盾,所以假设不成立,得证。

举个栗子:

A: 6 7 8

B: 1 2 3 4 5

找第8大的数字

2).A[mid] < B[mid] (midk/2 -1索引处的元素)。

这种情况下,我们可以丢弃Ak/2

证明:

我们使用反证法。

假设第K大在A的前k/2中记为maxK,例如位置在索引m(m<= k/2-1)那么B必然拥有前k中的k -(m+1)个元素,而

m <= k/2-1,则 m+1 <=k/2  , k - (m+1) > k/2

推出B[mid] <= maxK

而A[mid] >= maxK 推出A[mid]>=B[mid], 与题设矛盾。所以假设不能成立。

举个栗子:

A: 1 2

B: 4 5 6 7 8

找第四大的数字 我们就可以首先排除1,2.

 View Code

 2015.1.25

可以优化一下,在找到kth number时可以及时退出:


(3)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 Marcosfor contributing this image!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

我本来的思路:找到江江,然后升,直到再降,计算这一段内的盛水,但是没有考虑到后面可能有更高的柱子可以接水,这里面真的去想其实很难穷举可能性

网上的思路:基于动态规划Dynamic Programming的,遍历两遍数组,第一遍遍历dp[i]中存入i位置左边的最大值,然后开始第二遍遍历数组,第二次遍历时找右边最大值,然后和左边最大值比较取其中的较小值,然后跟当前值A[i]相比,如果大于当前值,则将差值存入结果

上述思路时间是2n, 更快n的做法: 从左右两边开始遍历,比较左右的大小,小的那个在小于最初始小的那个值时,均往前搜索,直到大于起始值,继续比较


(4)Candy

There are N children standing in a line. Each child is assigned a rating value.

You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

What is the minimum candies you must give?

Example 1:

Input: [1,0,2]
Output: 5
Explanation: You can allocate to the first, second and third child with 2, 1, 2 candies respectively.

Example 2:

Input: [1,2,2]
Output: 4
Explanation: You can allocate to the first, second and third child with 1, 2, 1 candies respectively.
             The third child gets 1 candy because it satisfies the above two conditions.
思路:这道题用到的思路和Trapping Rain Water是一样的,用动态规划。基本思路就是进行两次扫描,一次从左往右,一次从右往左。第一次扫描的时候维护对于每一个小孩左边所需要最少的糖果数量,存入数组对应元素中(与前一个数比),第二次扫描的时候维护右边所需的最少糖果数(与后一个数比),并且比较将左边和右边大的糖果数量存入结果数组对应元素中。这样两遍扫描之后就可以得到每一个所需要的最最少糖果量,从而累加得出结果。方法只需要两次扫描,所以时间复杂度是O(2*n)=O(n)。空间上需要一个长度为n的数组,复杂度是O(n)。

这种两边扫描的方法是一种比较常用的技巧,LeetCode中Trapping Rain Water和这道题都用到了,可以把这种方法作为自己思路的一部分,通常是要求的变量跟左右元素有关系的题目会用到哈。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值