Press "Enter" to skip to content

Huahua's Tech Road

花花酱 LeetCode 2023. Number of Pairs of Strings With Concatenation Equal to Target

方法1: Brute Force

枚举所有的(nums[i], nums[j])组合,相加在和target比较。

时间复杂度:O(mn2) m为字符串的最长长度。
空间复杂度:O(m)

优化前 67ms, 49.3M

一些工程上的优化

  • 用string_view作为参数类型,减少一次string copy
  • 先比较长度,再判断内容。
  • string_view.substr 是O(1)时间,和直接用strncmp比较内容是一样的。

优化后 3ms, 12.88MB

花花酱 LeetCode 2016. Maximum Difference Between Increasing Elements

数据规模 n <= 1000。O(n2) 的算法也是能过的。

方法1: Brute Force

双重循环枚举所有的(nums[i], nums[j])的组合。

时间复杂度:O(n2)
空间复杂度:O(1)

方法2: 空间换时间

使用prefix sum算法,预先计算num[i] ~ nums[n-1]的最大值,存储在right[i]中。

时间复杂度:O(n)
空间复杂度:O(n)

方法3: Running Min

从左到右遍历,记录当前为止出现过最小的值。比较 nums[i] – 最小值 和 最优解。

时间复杂度:O(n)
空间复杂度:O(1)

花花酱 LeetCode 2012. Sum of Beauty in the Array

数据规模比较大,算法必须是O(n)的。

可以预先使用O(n)时间计算nums[0] .. nums[i]的最大值,存在left[i]中,以及nums[i] .. nums[n-1]的最小值存在right[i]中。然后再按题目的定义计算即可。

时间复杂度:O(n)
空间复杂度:O(n)

花花酱 LeetCode 2011. Final Value of Variable After Performing Operations

C++ 也能写one-liner了。

时间复杂度:O(n)
空间复杂度:O(1)

花花酱 LeetCode 1992. Find All Groups of Farmland

已经告诉你所有的农田都是规整的矩形,题目难度一下子降低了。
对于每一个农田的左上角,找到它的宽度和高度即可。
然后把整个农田矩形标记为林地/非农田即可。

时间复杂度:O(m*n) 每个格子最多遍历3遍。
空间复杂度:O(1)