├── .gitignore ├── LICENSE ├── README.md ├── leetcode-cn.py ├── leetcode.cpp ├── leetcode.go ├── leetcode.java ├── leetcode.js ├── leetcode.pandas ├── leetcode.py ├── leetcode.rs ├── leetcode.sh ├── leetcode.sql └── leetcode.ts /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | *-internal.* 3 | *.code-workspace 4 | *.sublime-project 5 | *.sublime-workspace 6 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Ye Gao 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Welcome to my LeetCode solutions 2 | This repo collects my solutions to LeetCode problems in C++, Java and Python3. 3 | 4 | As new problems come up in weekly and biweekly contests, I will update this repo 5 | once the contests are over. Here, I try my best to make every solution as self- 6 | contained as possible. Due to the limited space, the details of the algorithms 7 | are not given. The readers are encouraged to look them up. Some good resources 8 | include 9 | 10 | * "Algorithms, Part I & Part II" by prof. Robert Sedgewick from Princeton 11 | University 12 | + https://www.coursera.org/learn/algorithms-part1 13 | + https://www.coursera.org/learn/algorithms-part2 14 | * "Algorithms Specialization" by prof. Tim Roughgarden from Stanford University 15 | + https://www.coursera.org/specializations/algorithms 16 | 17 | In addition, relevant implementations are available in my cp_algorithms repo. 18 | -------------------------------------------------------------------------------- /leetcode-cn.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | 4 | """LCP 06. 拿硬币 (简单) 5 | 桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走 6 | 其中的一枚或者两枚,求拿完所有力扣币的最少次数。 7 | 8 | 示例 1: 9 | 输入:[4,2,1] 10 | 输出:4 11 | 解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次, 12 | 总共 4 次即可拿完。 13 | 14 | 示例 2: 15 | 输入:[2,3,10] 16 | 输出:8 17 | 18 | 限制: 19 | * 1 <= n <= 4 20 | * 1 <= coins[i] <= 10""" 21 | 22 | def minCount(self, coins: List[int]) -> int: 23 | return sum((x+1)//2 for x in coins) 24 | 25 | 26 | """LCP 07. 传递信息 (简单) 27 | 小朋友 A 在和 ta 的小伙伴们玩传信息游戏,游戏规则如下: 28 | * 有 n 名玩家,所有玩家编号分别为 0 ~ n-1,其中小朋友 A 的编号为 0 29 | * 每个玩家都有固定的若干个可传信息的其他玩家(也可能没有)。传信息的关系是单向的(比如 30 | A 可以向 B 传信息,但 B 不能向 A 传信息)。 31 | * 每轮信息必须需要传递给另一个人,且信息可重复经过同一个人 32 | 给定总玩家数 n,以及按 [玩家编号,对应可传递玩家编号] 关系组成的二维数组 relation。 33 | 返回 信息从小 A (编号 0 ) 经过 k 轮传递到编号为 n-1 的小伙伴处的方案数;若不能到达, 34 | 返回 0。 35 | 36 | 示例 1: 37 | 输入:n = 5, relation = [[0,2],[2,1],[3,4],[2,3],[1,4],[2,0],[0,4]], k = 3 38 | 输出:3 39 | 解释:信息从小 A 编号 0 处开始,经 3 轮传递,到达编号 4。共有 3 种方案,分别是 40 | 0->2->0->4, 0->2->1->4, 0->2->3->4。 41 | 42 | 示例 2: 43 | 输入:n = 3, relation = [[0,2],[2,1]], k = 2 44 | 输出:0 45 | 解释:信息不能从小 A 处经过 2 轮传递到编号 2 46 | 47 | 限制: 48 | * 2 <= n <= 10 49 | * 1 <= k <= 5 50 | * 1 <= relation.length <= 90, 且 relation[i].length == 2 51 | * 0 <= relation[i][0],relation[i][1] < n 且 relation[i][0] != relation[i][1]""" 52 | 53 | def numWays(self, n: int, relation: List[List[int]], k: int) -> int: 54 | graph = [[] for _ in range(n)] 55 | for u, v in relation: graph[u].append(v) 56 | 57 | @cache 58 | def fn(x, i): 59 | """Return number of ways to reach x with i steps.""" 60 | if i == k: return x == n-1 61 | ans = 0 62 | for xx in graph[x]: ans += fn(xx, i+1) 63 | return ans 64 | 65 | return fn(0, 0) 66 | 67 | 68 | """LCP 11. 期望个数统计 (简单) 69 | 某互联网公司一年一度的春招开始了,一共有 n 名面试者入选。每名面试者都会提交一份简历,公 70 | 司会根据提供的简历资料产生一个预估的能力值,数值越大代表越有可能通过面试。小 A 和小 B 71 | 负责审核面试者,他们均有所有面试者的简历,并且将各自根据面试者能力值从大到小的顺序浏览。 72 | 由于简历事先被打乱过,能力值相同的简历的出现顺序是从它们的全排列中等可能地取一个。现在给 73 | 定 n 名面试者的能力值 scores,设 X 代表小 A 和小 B 的浏览顺序中出现在同一位置的简历数, 74 | 求 X 的期望。 提示:离散的非负随机变量的期望计算公式为 1。在本题中,由于 X 的取值为 0 到 75 | n 之间,期望计算公式可以是 2。 76 | 77 | 示例 1: 78 | 输入:scores = [1,2,3] 79 | 输出:3 80 | 解释:由于面试者能力值互不相同,小 A 和小 B 的浏览顺序一定是相同的。X的期望是 3 。 81 | 82 | 示例 2: 83 | 输入:scores = [1,1] 84 | 输出:1 85 | 解释:设两位面试者的编号为 0, 1。由于他们的能力值都是 1,小 A 和小 B 的浏览顺序都为从全 86 | 排列 [[0,1],[1,0]] 中等可能地取一个。如果小 A 和小 B 的浏览顺序都是 [0,1] 或者 87 | [1,0] ,那么出现在同一位置的简历数为 2 ,否则是 0 。所以 X 的期望是 88 | (2+0+2+0) * 1/4 = 1 89 | 90 | 示例 3: 91 | 输入:scores = [1,1,2] 92 | 输出:2 93 | 94 | 限制: 95 | * 1 <= scores.length <= 10^5 96 | * 0 <= scores[i] <= 10^6""" 97 | 98 | def expectNumber(self, scores: List[int]) -> int: 99 | return len(set(scores)) 100 | 101 | 102 | """LCP 17. 速算机器人 (简单) 103 | 小扣在秋日市集发现了一款速算机器人。店家对机器人说出两个数字(记作 x 和 y),请小扣说出 104 | 计算指令: 105 | * "A" 运算:使 x = 2 * x + y; 106 | * "B" 运算:使 y = 2 * y + x。 107 | 在本次游戏中,店家说出的数字为 x = 1 和 y = 0,小扣说出的计算指令记作仅由大写字母 A、B 108 | 组成的字符串 s,字符串中字符的顺序表示计算顺序,请返回最终 x 与 y 的和为多少。 109 | 110 | 示例 1: 111 | 输入:s = "AB" 112 | 输出:4 113 | 解释:经过一次 A 运算后,x = 2, y = 0。再经过一次 B 运算,x = 2, y = 2。最终 x 与 y 114 | 之和为 4。 115 | 116 | 提示: 117 | * 0 <= s.length <= 10 118 | * s 由 'A' 和 'B' 组成""" 119 | 120 | def calculate(self, s: str) -> int: 121 | return 2**len(s) 122 | 123 | 124 | """LCP 18. 早餐组合 (简单) 125 | 小扣在秋日市集选择了一家早餐摊位,一维整型数组 staple 中记录了每种主食的价格,一维整型 126 | 数组 drinks 中记录了每种饮料的价格。小扣的计划选择一份主食和一款饮料,且花费不超过 x 元。 127 | 请返回小扣共有多少种购买方案。注意:答案需要以 1e9 + 7 (1000000007) 为底取模,如:计算 128 | 初始结果为:1000000008,请返回 1 129 | 130 | 示例 1: 131 | 输入:staple = [10,20,5], drinks = [5,5,2], x = 15 132 | 输出:6 133 | 解释:小扣有 6 种购买方案,所选主食与所选饮料在数组中对应的下标分别是: 134 | 第 1 种方案:staple[0] + drinks[0] = 10 + 5 = 15; 135 | 第 2 种方案:staple[0] + drinks[1] = 10 + 5 = 15; 136 | 第 3 种方案:staple[0] + drinks[2] = 10 + 2 = 12; 137 | 第 4 种方案:staple[2] + drinks[0] = 5 + 5 = 10; 138 | 第 5 种方案:staple[2] + drinks[1] = 5 + 5 = 10; 139 | 第 6 种方案:staple[2] + drinks[2] = 5 + 2 = 7。 140 | 141 | 示例 2: 142 | 输入:staple = [2,1,1], drinks = [8,9,5,1], x = 9 143 | 输出:8 144 | 解释:小扣有 8 种购买方案,所选主食与所选饮料在数组中对应的下标分别是: 145 | 第 1 种方案:staple[0] + drinks[2] = 2 + 5 = 7; 146 | 第 2 种方案:staple[0] + drinks[3] = 2 + 1 = 3; 147 | 第 3 种方案:staple[1] + drinks[0] = 1 + 8 = 9; 148 | 第 4 种方案:staple[1] + drinks[2] = 1 + 5 = 6; 149 | 第 5 种方案:staple[1] + drinks[3] = 1 + 1 = 2; 150 | 第 6 种方案:staple[2] + drinks[0] = 1 + 8 = 9; 151 | 第 7 种方案:staple[2] + drinks[2] = 1 + 5 = 6; 152 | 第 8 种方案:staple[2] + drinks[3] = 1 + 1 = 2; 153 | 154 | 提示: 155 | * 1 <= staple.length <= 10^5 156 | * 1 <= drinks.length <= 10^5 157 | * 1 <= staple[i],drinks[i] <= 10^5 158 | * 1 <= x <= 2*10^5""" 159 | 160 | def breakfastNumber(self, staple: List[int], drinks: List[int], x: int) -> int: 161 | drinks.sort() 162 | ans, i = 0, len(drinks)-1 163 | for v in sorted(staple): 164 | while 0 <= i and v + drinks[i] > x: i -= 1 165 | ans += i+1 166 | return ans % 1_000_000_007 167 | 168 | 169 | """LCP 22. 黑白方格画 (简单) 170 | 小扣注意到秋日市集上有一个创作黑白方格画的摊位。摊主给每个顾客提供一个固定在墙上的白色画板, 171 | 画板不能转动。画板上有 n * n 的网格。绘画规则为,小扣可以选择任意多行以及任意多列的格子涂 172 | 成黑色(选择的整行、整列均需涂成黑色),所选行数、列数均可为 0。小扣希望最终的成品上需要有 k 173 | 个黑色格子,请返回小扣共有多少种涂色方案。注意:两个方案中任意一个相同位置的格子颜色不同, 174 | 就视为不同的方案。 175 | 176 | 示例 1: 177 | 输入:n = 2, k = 2 178 | 输出:4 179 | 解释:一共有四种不同的方案: 180 | 第一种方案:涂第一列; 181 | 第二种方案:涂第二列; 182 | 第三种方案:涂第一行; 183 | 第四种方案:涂第二行。 184 | 185 | 示例 2: 186 | 输入:n = 2, k = 1 187 | 输出:0 188 | 解释:不可行,因为第一次涂色至少会涂两个黑格。 189 | 190 | 示例 3: 191 | 输入:n = 2, k = 4 192 | 输出:1 193 | 解释:共有 2*2=4 个格子,仅有一种涂色方案。 194 | 195 | 限制: 196 | * 1 <= n <= 6 197 | * 0 <= k <= n * n""" 198 | 199 | def paintingPlan(self, n: int, k: int) -> int: 200 | white = n*n - k 201 | if white == 0: return 1 # edge case 202 | ans = 0 203 | for row in range(1, int(sqrt(white))+1): 204 | if row <= n: 205 | if white % row == 0: 206 | col = white // row 207 | if col <= n: 208 | if row == col: ans += comb(n, row) * comb(n, col) 209 | else: ans += 2*comb(n, row) * comb(n, col) 210 | return ans 211 | 212 | 213 | """LCP 33. 蓄水 (简单) 214 | 给定 N 个无限容量且初始均空的水缸,每个水缸配有一个水桶用来打水,第 i 个水缸配备的水桶 215 | 容量记作 bucket[i]。小扣有以下两种操作: 216 | * 升级水桶:选择任意一个水桶,使其容量增加为 bucket[i]+1 217 | * 蓄水:将全部水桶接满水,倒入各自对应的水缸 218 | 每个水缸对应最低蓄水量记作 vat[i],返回小扣至少需要多少次操作可以完成所有水缸蓄水要求。 219 | 注意:实际蓄水量 达到或超过 最低蓄水量,即完成蓄水要求。 220 | 221 | 示例 1: 222 | 输入:bucket = [1,3], vat = [6,8] 223 | 输出:4 224 | 解释:第 1 次操作升级 bucket[0]; 225 | 第 2 ~ 4 次操作均选择蓄水,即可完成蓄水要求。 226 | 227 | 示例 2: 228 | 输入:bucket = [9,0,1], vat = [0,2,2] 229 | 输出:3 230 | 解释:第 1 次操作均选择升级 bucket[1] 231 | 第 2~3 次操作选择蓄水,即可完成蓄水要求。 232 | 233 | 提示: 234 | * 1 <= bucket.length == vat.length <= 100 235 | * 0 <= bucket[i], vat[i] <= 10^4""" 236 | 237 | def storeWater(self, bucket: List[int], vat: List[int]) -> int: 238 | pq = [] 239 | pre = 0 # pre-processing 240 | for b, v in zip(bucket, vat): 241 | if v: 242 | if b == 0: b, pre = 1, pre+1 243 | heappush(pq, (-ceil(v/b), b, v)) 244 | inc = 0 245 | ans = inf 246 | while pq and inc < ans: 247 | x, b, v = heappop(pq) 248 | ans = min(ans, inc - x) 249 | if -x <= 2: break 250 | heappush(pq, (-ceil(v/(b+1)), b+1, v)) 251 | inc += 1 252 | return pre + (ans if ans < inf else 0) 253 | 254 | 255 | """LCP 39. 无人机方阵 (简单) 256 | 在 「力扣挑战赛」 开幕式的压轴节目 「无人机方阵」中,每一架无人机展示一种灯光颜色。 无人机方 257 | 阵通过两种操作进行颜色图案变换: 258 | * 调整无人机的位置布局 259 | * 切换无人机展示的灯光颜色 260 | 给定两个大小均为 N*M 的二维数组 source 和 target 表示无人机方阵表演的两种颜色图案,由 261 | 于无人机切换灯光颜色的耗能很大,请返回从 source 到 target 最少需要多少架无人机切换灯光 262 | 颜色。注意: 调整无人机的位置布局时无人机的位置可以随意变动。 263 | 264 | 示例 1: 265 | 输入:source = [[1,3],[5,4]], target = [[3,1],[6,5]] 266 | 输出:1 267 | 解释:最佳方案为 268 | 将 [0,1] 处的无人机移动至 [0,0] 处; 269 | 将 [0,0] 处的无人机移动至 [0,1] 处; 270 | 将 [1,0] 处的无人机移动至 [1,1] 处; 271 | 将 [1,1] 处的无人机移动至 [1,0] 处,其灯光颜色切换为颜色编号为 6 的灯光; 272 | 因此从source 到 target 所需要的最少灯光切换次数为 1。 273 | 274 | 示例 2: 275 | 输入:source = [[1,2,3],[3,4,5]], target = [[1,3,5],[2,3,4]] 276 | 输出:0 277 | 解释:仅需调整无人机的位置布局,便可完成图案切换。因此不需要无人机切换颜色 278 | 279 | 提示: 280 | * n == source.length == target.length 281 | * m == source[i].length == target[i].length 282 | * 1 <= n, m <=100 283 | * 1 <= source[i][j], target[i][j] <=10^4""" 284 | 285 | def minimumSwitchingTimes(self, source: List[List[int]], target: List[List[int]]) -> int: 286 | freq = Counter() 287 | for row in source: 288 | for x in row: freq[x] += 1 289 | for row in target: 290 | for x in row: freq[x] -= 1 291 | return sum(map(abs, freq.values()))//2 292 | 293 | 294 | """LCP 40. 心算挑战 (简单) 295 | 「力扣挑战赛」心算项目的挑战比赛中,要求选手从 N 张卡牌中选出 cnt 张卡牌,若这 cnt 296 | 张卡牌数字总和为偶数,则选手成绩「有效」且得分为 cnt 张卡牌数字总和。给定数组 cards 297 | 和 cnt,其中 cards[i] 表示第 i 张卡牌上的数字。 请帮参赛选手计算最大的有效得分。 298 | 若不存在获取有效得分的卡牌方案,则返回 0。 299 | 300 | 示例 1: 301 | 输入:cards = [1,2,8,9], cnt = 3 302 | 输出:18 303 | 解释:选择数字为 1、8、9 的这三张卡牌,此时可获得最大的有效得分 1+8+9=18。 304 | 305 | 示例 2: 306 | 输入:cards = [3,3,1], cnt = 1 307 | 输出:0 308 | 解释:不存在获取有效得分的卡牌方案。 309 | 310 | 提示: 311 | * 1 <= cnt <= cards.length <= 10^5 312 | * 1 <= cards[i] <= 1000""" 313 | 314 | def maxmiumScore(self, cards: List[int], cnt: int) -> int: 315 | odd, even = [0], [0] 316 | for x in sorted(cards, reverse=True): 317 | if x & 1: odd.append(odd[-1] + x) 318 | else: even.append(even[-1] + x) 319 | ans = 0 320 | for k in range(0, cnt+1, 2): 321 | if k < len(odd) and cnt-k < len(even): ans = max(ans, odd[k] + even[cnt-k]) 322 | return ans 323 | 324 | 325 | """LCP 41. 黑白翻转棋 (中等) 326 | 在 n*m 大小的棋盘中,有黑白两种棋子,黑棋记作字母 "X", 白棋记作字母 "O",空余位置 327 | 记作 "."。当落下的棋子与其他相同颜色的棋子在行、列或对角线完全包围(中间不存在空白位 328 | 置)另一种颜色的棋子,则可以翻转这些棋子的颜色。 329 | 330 | 「力扣挑战赛」黑白翻转棋项目中,将提供给选手一个未形成可翻转棋子的棋盘残局,其状态记作 331 | chessboard。若下一步可放置一枚黑棋,请问选手最多能翻转多少枚白棋。 332 | 333 | 注意: 334 | * 若翻转白棋成黑棋后,棋盘上仍存在可以翻转的白棋,将可以 继续 翻转白棋 335 | * 输入数据保证初始棋盘状态无可以翻转的棋子且存在空余位置 336 | 337 | 示例 1: 338 | 输入:chessboard = ["....X.","....X.","XOOO..","......","......"] 339 | 输出:3 340 | 解释:可以选择下在 [2,4] 处,能够翻转白方三枚棋子。 341 | 342 | 示例 2: 343 | 输入:chessboard = [".X.",".O.","XO."] 344 | 输出:2 345 | 解释:可以选择下在 [2,2] 处,能够翻转白方两枚棋子。 346 | 347 | 示例 3: 348 | 输入:chessboard = [".......",".......",".......","X......",".O.....","..O....","....OOX"] 349 | 输出:4 350 | 解释:可以选择下在 [6,3] 处,能够翻转白方四枚棋子。 351 | 352 | 提示: 353 | * 1 <= chessboard.length, chessboard[i].length <= 8 354 | * chessboard[i] 仅包含 "."、"O" 和 "X" """ 355 | 356 | def flipChess(self, chessboard: List[str]) -> int: 357 | chessboard = [list(x) for x in chessboard] 358 | m, n = len(chessboard), len(chessboard[0]) 359 | 360 | def fn(i, j): 361 | """Return position of 'O' flipped when placing a 'X' at (i, j).""" 362 | ans = [] 363 | for di, dj in (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1): 364 | vals = [] 365 | ii, jj = i+di, j+dj 366 | while 0 <= ii < m and 0 <= jj < n and chessboard[ii][jj] != '.': 367 | if chessboard[ii][jj] == 'X': 368 | x, y = i+di, j+dj 369 | while (x, y) != (ii, jj): 370 | vals.append((x, y)) 371 | chessboard[x][y] = 'X' 372 | x, y = x+di, y+dj 373 | break 374 | ii, jj = ii+di, jj+dj 375 | ans.extend(vals) 376 | return ans 377 | 378 | ans = 0 379 | for r in range(m): 380 | for c in range(n): 381 | if chessboard[r][c] == '.': 382 | orig = deepcopy(chessboard) 383 | cand = 0 384 | stack = [(r, c)] 385 | chessboard[r][c] = 'X' 386 | while stack: 387 | i, j = stack.pop() 388 | vals = fn(i, j) 389 | cand += len(vals) 390 | stack.extend(vals) 391 | ans = max(ans, cand) 392 | chessboard = orig 393 | return ans 394 | 395 | 396 | """LCP 44. 开幕式焰火 (简单) 397 | 「力扣挑战赛」开幕式开始了,空中绽放了一颗二叉树形的巨型焰火。给定一棵二叉树 root 代表焰火, 398 | 节点值表示巨型焰火这一位置的颜色种类。请帮小扣计算巨型焰火有多少种不同的颜色。 399 | 400 | 示例 1: 401 | 输入:root = [1,3,2,1,null,2] 402 | 输出:3 403 | 解释:焰火中有 3 个不同的颜色,值分别为 1、2、3 404 | 405 | 示例 2: 406 | 输入:root = [3,3,3] 407 | 输出:1 408 | 解释:焰火中仅出现 1 个颜色,值为 3 409 | 410 | 提示: 411 | * 1 <= 节点个数 <= 1000 412 | * 1 <= Node.val <= 1000""" 413 | 414 | def numColor(self, root: TreeNode) -> int: 415 | seen = set() 416 | stack = [root] 417 | while stack: 418 | node = stack.pop() 419 | if node: 420 | seen.add(node.val) 421 | stack.append(node.right) 422 | stack.append(node.left) 423 | return len(seen) 424 | 425 | 426 | """LCP 45. 自行车炫技赛场 (中等) 427 | 「力扣挑战赛」中 N*M 大小的自行车炫技赛场的场地由一片连绵起伏的上下坡组成,场地的高度 428 | 值记录于二维数组 terrain 中,场地的减速值记录于二维数组 obstacle 中。 429 | 430 | * 若选手骑着自行车从高度为 h1 且减速值为 o1 的位置到高度为 h2 且减速值为 o2 的相邻 431 | 位置(上下左右四个方向),速度变化值为 h1-h2-o2(负值减速,正值增速)。 432 | 选手初始位于坐标 position 处且初始速度为 1,请问选手可以刚好到其他哪些位置时速度依 433 | 旧为 1。请以二维数组形式返回这些位置。若有多个位置则按行坐标升序排列,若有多个位置行 434 | 坐标相同则按列坐标升序排列。 435 | 436 | 注意: 骑行过程中速度不能为零或负值 437 | 438 | 示例 1: 439 | 输入:position = [0,0], terrain = [[0,0],[0,0]], obstacle = [[0,0],[0,0]] 440 | 输出:[[0,1],[1,0],[1,1]] 441 | 解释:由于当前场地属于平地,根据上面的规则,选手从[0,0]的位置出发都能刚好在其他处的 442 | 位置速度为 1。 443 | 444 | 示例 2: 445 | 输入:position = [1,1], terrain = [[5,0],[0,6]], obstacle = [[0,6],[7,0]] 446 | 输出:[[0,1]] 447 | 解释:选手从 [1,1] 处的位置出发,到 [0,1] 处的位置时恰好速度为 1。 448 | 449 | 提示: 450 | * n == terrain.length == obstacle.length 451 | * m == terrain[i].length == obstacle[i].length 452 | * 1 <= n <= 100 453 | * 1 <= m <= 100 454 | * 0 <= terrain[i][j], obstacle[i][j] <= 100 455 | * position.length == 2 456 | * 0 <= position[0] < n 457 | * 0 <= position[1] < m""" 458 | 459 | def bicycleYard(self, position: List[int], terrain: List[List[int]], obstacle: List[List[int]]) -> List[List[int]]: 460 | m, n = len(terrain), len(terrain[0]) 461 | ans = [] 462 | seen = {(*position, 1)} 463 | stack = [(*position, 1)] 464 | while stack: 465 | i, j, v = stack.pop() 466 | if v == 1 and [i, j] != position: ans.append([i, j]) 467 | for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j): 468 | if 0 <= ii < m and 0 <= jj < n: 469 | vv = v + terrain[i][j] - terrain[ii][jj] - obstacle[ii][jj] 470 | if vv > 0 and (ii, jj, vv) not in seen: 471 | seen.add((ii, jj, vv)) 472 | stack.append((ii, jj, vv)) 473 | return sorted(ans) 474 | 475 | 476 | """LCP 46. 志愿者调配 (中等) 477 | 「力扣挑战赛」有 n 个比赛场馆(场馆编号从 0 开始),场馆之间的通道分布情况记录于二维 478 | 数组 edges 中,edges[i]= [x, y] 表示第 i 条通道连接场馆 x 和场馆 y(即两个场馆相 479 | 邻)。初始每个场馆中都有一定人数的志愿者(不同场馆人数可能不同),后续 m 天每天均会 480 | 根据赛事热度进行志愿者人数调配。调配方案分为如下三种: 481 | * 将编号为 idx 的场馆内的志愿者人数减半; 482 | * 将编号为 idx 的场馆相邻的场馆的志愿者人数都加上编号为 idx 的场馆的志愿者人数; 483 | * 将编号为 idx 的场馆相邻的场馆的志愿者人数都减去编号为 idx 的场馆的志愿者人数。 484 | 所有的调配信息记录于数组 plans 中,plans[i] = [num,idx] 表示第 i 天对编号 idx 的 485 | 场馆执行了第 num 种调配方案。在比赛结束后对调配方案进行复盘时,不慎将第 0 个场馆的 486 | 最终志愿者人数丢失,只保留了初始所有场馆的志愿者总人数 totalNum ,以及记录了第 487 | 1 ~ n-1 个场馆的最终志愿者人数的一维数组 finalCnt。请你根据现有的信息求出初始每个 488 | 场馆的志愿者人数,并按场馆编号顺序返回志愿者人数列表。 489 | 490 | 注意: 491 | * 测试数据保证当某场馆进行第一种调配时,该场馆的志愿者人数一定为偶数; 492 | * 测试数据保证当某场馆进行第三种调配时,该场馆的相邻场馆志愿者人数不为负数; 493 | * 测试数据保证比赛开始时每个场馆的志愿者人数都不超过 10^9; 494 | * 测试数据保证给定的场馆间的道路分布情况中不会出现自环、重边的情况。 495 | 496 | 示例 1: 497 | 输入:finalCnt = [1,16], totalNum = 21, edges = [[0,1],[1,2]], plans = [[2,1],[1,0],[3,0]] 498 | 输出:[5,7,9] 499 | 500 | 示例 2 : 501 | 输入:finalCnt = [4,13,4,3,8], totalNum = 54, edges = [[0,3],[1,3],[4,3],[2,3],[2,5]], plans = [[1,1],[3,3],[2,5],[1,0]] 502 | 输出:[10,16,9,4,7,8] 503 | 504 | 提示: 505 | * 2 <= n <= 5*10^4 506 | * 1 <= edges.length <= min((n * (n - 1)) / 2, 5*10^4) 507 | * 0 <= edges[i][0], edges[i][1] < n 508 | * 1 <= plans.length <= 10 509 | * 1 <= plans[i][0] <=3 510 | * 0 <= plans[i][1] < n 511 | * finalCnt.length = n-1 512 | * 0 <= finalCnt[i] < 10^9 513 | * 0 <= totalNum < 5*10^13""" 514 | 515 | def volunteerDeployment(self, finalCnt: List[int], totalNum: int, edges: List[List[int]], plans: List[List[int]]) -> List[int]: 516 | n = 1 + len(finalCnt) 517 | graph = [[] for _ in range(n)] 518 | for u, v in edges: 519 | graph[u].append(v) 520 | graph[v].append(u) 521 | 522 | coef = [0]*n 523 | coef[0] = 1 524 | vals = [0] + finalCnt 525 | 526 | for num, idx in reversed(plans): 527 | if num == 1: 528 | coef[idx] *= 2 529 | vals[idx] *= 2 530 | elif num == 2: 531 | for x in graph[idx]: 532 | coef[x] -= coef[idx] 533 | vals[x] -= vals[idx] 534 | elif num == 3: 535 | for x in graph[idx]: 536 | coef[x] += coef[idx] 537 | vals[x] += vals[idx] 538 | 539 | delta = (totalNum - sum(vals))//sum(coef) 540 | return [delta*c+v for c, v in zip(coef, vals)] 541 | 542 | 543 | """LCS 01. 下载插件 (简单) 544 | 小扣打算给自己的 VS code 安装使用插件,初始状态下带宽每分钟可以完成 1 个插件的下载。 545 | 假定每分钟选择以下两种策略之一: 546 | * 使用当前带宽下载插件 547 | * 将带宽加倍(下载插件数量随之加倍) 548 | 请返回小扣完成下载 n 个插件最少需要多少分钟。注意:实际的下载的插件数量可以超过 n 个。 549 | 550 | 示例 1: 551 | 输入:n = 2 552 | 输出:2 553 | 解释:以下两个方案,都能实现 2 分钟内下载 2 个插件 554 | 方案一:第一分钟带宽加倍,带宽可每分钟下载 2 个插件;第二分钟下载 2 个插件 555 | 方案二:第一分钟下载 1 个插件,第二分钟下载 1 个插件 556 | 557 | 示例 2: 558 | 输入:n = 4 559 | 输出:3 560 | 解释:最少需要 3 分钟可完成 4 个插件的下载,以下是其中一种方案: 561 | 第一分钟带宽加倍,带宽可每分钟下载 2 个插件; 562 | 第二分钟下载 2 个插件; 563 | 第三分钟下载 2 个插件。 564 | 565 | 提示:1 <= n <= 10^5""" 566 | 567 | def leastMinutes(self, n: int) -> int: 568 | ans = 0 569 | while n > 1: 570 | ans += 1 571 | n = (n+1)//2 572 | return ans + 1 573 | 574 | 575 | """LCS 02. 完成一半题目 (简单) 576 | 有 N 位扣友参加了微软与力扣举办了「以扣会友」线下活动。主办方提供了 2*N 道题目,整型数组 577 | questions 中每个数字对应了每道题目所涉及的知识点类型。若每位扣友选择不同的一题,请返回 578 | 被选的 N 道题目至少包含多少种知识点类型。 579 | 580 | 示例 1: 581 | 输入:questions = [2,1,6,2] 582 | 输出:1 583 | 解释:有 2 位扣友在 4 道题目中选择 2 题。可选择完成知识点类型为 2 的题目时,此时仅一种 584 | 知识点类型因此至少包含 1 种知识点类型。 585 | 586 | 示例 2: 587 | 输入:questions = [1,5,1,3,4,5,2,5,3,3,8,6] 588 | 输出:2 589 | 解释:有 6 位扣友在 12 道题目中选择题目,需要选择 6 题。选择完成知识点类型为 3、5 的题 590 | 目,因此至少包含 2 种知识点类型。 591 | 592 | 提示: 593 | * questions.length == 2*n 594 | * 2 <= questions.length <= 10^5 595 | * 1 <= questions[i] <= 1000""" 596 | 597 | def halfQuestions(self, questions: List[int]) -> int: 598 | freq = Counter(questions) 599 | n = len(questions)//2 600 | ans = 0 601 | vals = sorted(freq.values()) 602 | while n > 0: 603 | ans += 1 604 | n -= vals.pop() 605 | return ans 606 | 607 | 608 | """剑指 Offer 03. 数组中重复的数字 (简单) 609 | 找出数组中重复的数字。在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组 610 | 中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任 611 | 意一个重复的数字。 612 | 613 | 示例 1: 614 | 输入:[2, 3, 1, 0, 2, 5, 3] 615 | 输出:2 或 3 616 | 617 | 限制:2 <= n <= 100000""" 618 | 619 | def findRepeatNumber(self, nums: List[int]) -> int: 620 | seen = set() 621 | for x in nums: 622 | if x in seen: return x 623 | seen.add(x) 624 | 625 | 626 | """剑指 Offer 05. 替换空格 (简单) 627 | 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 628 | 629 | 示例 1: 630 | 输入:s = "We are happy." 631 | 输出:"We%20are%20happy." 632 | 633 | 限制:0 <= s 的长度 <= 10000""" 634 | 635 | def replaceSpace(self, s: str) -> str: 636 | return s.replace(' ', "%20") 637 | 638 | 639 | """剑指 Offer 06. 从尾到头打印链表 (简单) 640 | 输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 641 | 642 | 示例 1: 643 | 输入:head = [1,3,2] 644 | 输出:[2,3,1] 645 | 646 | 限制:0 <= 链表长度 <= 10000""" 647 | 648 | def reversePrint(self, head: ListNode) -> List[int]: 649 | ans = [] 650 | node = head 651 | while node: 652 | ans.append(node.val) 653 | node = node.next 654 | return ans[::-1] 655 | 656 | 657 | """剑指 Offer 10- I. 斐波那契数列 (简单) 658 | 写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(N))。斐波那契数列的定义如下: 659 | * F(0) = 0, F(1) = 1 660 | * F(N) = F(N - 1) + F(N - 2), 其中 N > 1. 661 | 斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。答案需要取模 1e9+7 662 | (1000000007),如计算初始结果为:1000000008,请返回 1。 663 | 664 | 示例 1: 665 | 输入:n = 2 666 | 输出:1 667 | 668 | 示例 2: 669 | 输入:n = 5 670 | 输出:5 671 | 672 | 提示:0 <= n <= 100""" 673 | 674 | def fib(self, n: int) -> int: 675 | f0, f1 = 0, 1 676 | for _ in range(n): f0, f1 = f1, (f0+f1) % 1_000_000_007 677 | return f0 678 | 679 | 680 | """剑指 Offer 10- II. 青蛙跳台阶问题 (简单) 681 | 一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个 n 级的台阶总共有多少种跳法。 682 | 答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。 683 | 684 | 示例 1: 685 | 输入:n = 2 686 | 输出:2 687 | 688 | 示例 2: 689 | 输入:n = 7 690 | 输出:21 691 | 692 | 示例 3: 693 | 输入:n = 0 694 | 输出:1 695 | 696 | 提示:0 <= n <= 100""" 697 | 698 | def numWays(self, n: int) -> int: 699 | f0, f1 = 1, 1 700 | for _ in range(n): f0, f1 = f1, (f0+f1) % 1_000_000_007 701 | return f0 702 | 703 | 704 | """剑指 Offer 11. 旋转数组的最小数字 (简单) 705 | 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。输入一个递增排序的数组的一个 706 | 旋转,输出旋转数组的最小元素。例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小 707 | 值为1。 708 | 709 | 示例 1: 710 | 输入:[3,4,5,1,2] 711 | 输出:1 712 | 713 | 示例 2: 714 | 输入:[2,2,2,0,1] 715 | 输出:0 716 | 注意:本题与主站 154 题相同: 717 | https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array-ii/""" 718 | 719 | def minArray(self, numbers: List[int]) -> int: 720 | lo, hi = 0, len(numbers)-1 721 | while lo < hi: 722 | mid = lo + hi >> 1 723 | if numbers[mid] < numbers[hi]: hi = mid 724 | elif numbers[mid] == numbers[hi]: hi -= 1 725 | else: lo = mid + 1 726 | return numbers[lo] 727 | 728 | 729 | """剑指 Offer 14- I. 剪绳子 (中等) 730 | 给你一根长度为 n 的绳子,请把绳子剪成整数长度的 m 段(m、n都是整数,n>1并且m>1), 731 | 每段绳子的长度记为 k[0],k[1]...k[m-1] 。请问 k[0]*k[1]*...*k[m-1] 可能的最大 732 | 乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到 733 | 的最大乘积是18。 734 | 735 | 示例 1: 736 | 输入: 2 737 | 输出: 1 738 | 解释: 2 = 1 + 1, 1 × 1 = 1 739 | 740 | 示例 2: 741 | 输入: 10 742 | 输出: 36 743 | 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36 744 | 745 | 提示: 746 | * 2 <= n <= 58 747 | * 注意:本题与主站 343 题相同:https://leetcode-cn.com/problems/integer-break/""" 748 | 749 | def cuttingRope(self, n: int) -> int: 750 | if n == 2: return 1 751 | if n == 3: return 2 752 | if n % 3 == 0: return 3**(n//3) 753 | if n % 3 == 1: return 3**((n-4)//3) * 4 754 | return 3**((n-2)//3) * 2 755 | 756 | 757 | """剑指 Offer 15. 二进制中1的个数 (简单) 758 | 编写一个函数,输入是一个无符号整数(以二进制串的形式),返回其二进制表达式中数字位数为 '1' 759 | 的个数(也被称为 汉明重量).)。 760 | 761 | 提示:请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指 762 | 定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部 763 | 的二进制表示形式都是相同的。在 Java 中,编译器使用 二进制补码 记法来表示有符号整数。 764 | 因此,在上面的 示例 3 中,输入表示有符号整数 -3。 765 | 766 | 示例 1: 767 | 输入:n = 11 (控制台输入 00000000000000000000000000001011) 768 | 输出:3 769 | 解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。 770 | 771 | 示例 2: 772 | 输入:n = 128 (控制台输入 00000000000000000000000010000000) 773 | 输出:1 774 | 解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'。 775 | 776 | 示例 3: 777 | 输入:n = 4294967293 (控制台输入 11111111111111111111111111111101,部分语言中 n = -3) 778 | 输出:31 779 | 解释:输入的二进制串 11111111111111111111111111111101 中,共有 31 位为 '1'。 780 | 781 | 提示:输入必须是长度为 32 的 二进制串 。""" 782 | 783 | def hammingWeight(self, n: int) -> int: 784 | ans = 0 785 | while n: 786 | ans += 1 787 | n &= n-1 788 | return ans 789 | 790 | 791 | """剑指 Offer 17. 打印从1到最大的n位数 (简单) 792 | 输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到 793 | 最大的 3 位数 999。 794 | 795 | 示例 1: 796 | 输入: n = 1 797 | 输出: [1,2,3,4,5,6,7,8,9] 798 | 799 | 说明: 800 | * 用返回一个整数列表来代替打印 801 | * n 为正整数""" 802 | 803 | def printNumbers(self, n: int) -> List[int]: 804 | return list(range(1, 10**n)) 805 | 806 | 807 | """剑指 Offer 18. 删除链表的节点 (简单) 808 | 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。 809 | 注意:此题对比原题有改动 810 | 811 | 示例 1: 812 | 输入: head = [4,5,1,9], val = 5 813 | 输出: [4,1,9] 814 | 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9. 815 | 816 | 示例 2: 817 | 输入: head = [4,5,1,9], val = 1 818 | 输出: [4,5,9] 819 | 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9. 820 | 821 | 说明: 822 | * 题目保证链表中节点的值互不相同 823 | * 若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点""" 824 | 825 | def deleteNode(self, head: ListNode, val: int) -> ListNode: 826 | dummy = node = ListNode(next=head) 827 | while node.next: 828 | if node.next.val == val: 829 | node.next = node.next.next 830 | break 831 | node = node.next 832 | return dummy.next 833 | 834 | 835 | """剑指 Offer 21. 调整数组顺序使奇数位于偶数前面 (简单) 836 | 输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数在数组的前半部分,所有偶数 837 | 在数组的后半部分。 838 | 839 | 示例: 840 | 输入:nums = [1,2,3,4] 841 | 输出:[1,3,2,4] 842 | 注:[3,1,2,4] 也是正确的答案之一。 843 | 844 | 提示: 845 | * 0 <= nums.length <= 50000 846 | * 0 <= nums[i] <= 10000""" 847 | 848 | def exchange(self, nums: List[int]) -> List[int]: 849 | lo, hi = 0, len(nums)-1 850 | while lo < hi: 851 | if nums[lo] & 1: lo += 1 852 | elif not nums[hi] & 1: hi -= 1 853 | else: 854 | nums[lo], nums[hi] = nums[hi], nums[lo] 855 | lo += 1 856 | hi -= 1 857 | return nums 858 | 859 | 860 | """剑指 Offer 22. 链表中倒数第k个节点 (简单) 861 | 输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表 862 | 的尾节点是倒数第1个节点。例如,一个链表有 6 个节点,从头节点开始,它们的值依次是 863 | 1、2、3、4、5、6。这个链表的倒数第 3 个节点是值为 4 的节点。 864 | 865 | 示例:给定一个链表: 1->2->3->4->5, 和 k = 2. 866 | 返回链表 4->5.""" 867 | 868 | def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: 869 | fast = slow = head 870 | while fast: 871 | fast = fast.next 872 | k -= 1 873 | if k < 0: slow = slow.next 874 | return slow 875 | 876 | 877 | """剑指 Offer 24. 反转链表 (简单) 878 | 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。 879 | 880 | 示例: 881 | 输入: 1->2->3->4->5->NULL 882 | 输出: 5->4->3->2->1->NULL 883 | 884 | 限制:0 <= 节点个数 <= 5000 885 | 注意:本题与主站 206 题相同:https://leetcode-cn.com/problems/reverse-linked-list/""" 886 | 887 | def reverseList(self, head: ListNode) -> ListNode: 888 | prev, node = None, head 889 | while node: node.next, node, prev = prev, node.next, node 890 | return prev 891 | 892 | 893 | """剑指 Offer 25. 合并两个排序的链表 (简单) 894 | 输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。 895 | 896 | 示例1: 897 | 输入:1->2->4, 1->3->4 898 | 输出:1->1->2->3->4->4 899 | 900 | 限制:0 <= 链表长度 <= 1000 901 | 注意:本题与主站 21 题相同:https://leetcode-cn.com/problems/merge-two-sorted-lists/""" 902 | 903 | def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 904 | dummy = node = ListNode() 905 | while l1 and l2: 906 | if l1.val <= l2.val: 907 | node.next = node = l1 908 | l1 = l1.next 909 | else: 910 | node.next = node = l2 911 | l2 = l2.next 912 | node.next = l1 or l2 913 | return dummy.next 914 | 915 | 916 | """剑指 Offer 27. 二叉树的镜像 (简单) 917 | 请完成一个函数,输入一个二叉树,该函数输出它的镜像。 918 | 919 | 例如输入: 4 920 | / \ 921 | 2 7 922 | / \ / \ 923 | 1 3 6 9 924 | 镜像输出: 4 925 | / \ 926 | 7 2 927 | / \ / \ 928 | 9 6 3 1 929 | 930 | 示例 1: 931 | 输入:root = [4,2,7,1,3,6,9] 932 | 输出:[4,7,2,9,6,3,1] 933 | 934 | 限制:0 <= 节点个数 <= 1000 935 | 注意:本题与主站 226 题相同:https://leetcode-cn.com/problems/invert-binary-tree/""" 936 | 937 | def mirrorTree(self, root: TreeNode) -> TreeNode: 938 | stack = [root] 939 | while stack: 940 | node = stack.pop() 941 | if node: 942 | node.left, node.right = node.right, node.left 943 | stack.append(node.right) 944 | stack.append(node.left) 945 | return root 946 | 947 | 948 | """剑指 Offer 28. 对称的二叉树 (简单) 949 | 请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称 950 | 的。例如,二叉树 [1,2,2,3,4,4,3] 是对称的。 951 | 1 952 | / \ 953 | 2 2 954 | / \ / \ 955 | 3 4 4 3 956 | 但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的: 957 | 1 958 | / \ 959 | 2 2 960 | \ \ 961 | 3 3 962 | 963 | 示例 1: 964 | 输入:root = [1,2,2,3,4,4,3] 965 | 输出:true 966 | 967 | 示例 2: 968 | 输入:root = [1,2,2,null,3,null,3] 969 | 输出:false 970 | 971 | 限制:0 <= 节点个数 <= 1000 972 | 注意:本题与主站 101 题相同:https://leetcode-cn.com/problems/symmetric-tree/""" 973 | 974 | def isSymmetric(self, root: TreeNode) -> bool: 975 | stack = [(root, root)] 976 | while stack: 977 | p, q = stack.pop() 978 | if p or q: 979 | if not p or not q or p.val != q.val: return False 980 | stack.append((p.left, q.right)) 981 | stack.append((p.right, q.left)) 982 | return True 983 | 984 | 985 | """剑指 Offer 29. 顺时针打印矩阵 (简单) 986 | 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。 987 | 988 | 示例 1: 989 | 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]] 990 | 输出:[1,2,3,6,9,8,7,4,5] 991 | 992 | 示例 2: 993 | 输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] 994 | 输出:[1,2,3,4,8,12,11,10,9,5,6,7] 995 | 996 | 限制: 997 | * 0 <= matrix.length <= 100 998 | * 0 <= matrix[i].length <= 100 999 | 1000 | 注意:本题与主站 54 题相同:https://leetcode-cn.com/problems/spiral-matrix/""" 1001 | 1002 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 1003 | ans = [] 1004 | if matrix: 1005 | m, n = len(matrix), len(matrix[0]) 1006 | i = j = 0 1007 | di, dj = 0, 1 1008 | for _ in range(m*n): 1009 | ans.append(matrix[i][j]) 1010 | matrix[i][j] = None # mark "visited" 1011 | if not (0 <= i+di < m and 0 <= j+dj < n and matrix[i+di][j+dj] is not None): di, dj = dj, -di 1012 | i, j = i+di, j+dj 1013 | return ans 1014 | 1015 | 1016 | """剑指 Offer 32 - II. 从上到下打印二叉树 II (简单) 1017 | 从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。 1018 | 1019 | 例如: 1020 | 给定二叉树: [3,9,20,null,null,15,7], 1021 | 3 1022 | / \ 1023 | 9 20 1024 | / \ 1025 | 15 7 1026 | 返回其层次遍历结果:[[3], 1027 | [9,20], 1028 | [15,7]] 1029 | 1030 | 提示:节点总数 <= 1000 1031 | 注意:本题与主站 102 题相同:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/""" 1032 | 1033 | def levelOrder(self, root: TreeNode) -> List[List[int]]: 1034 | ans = [] 1035 | if root: 1036 | queue = deque([root]) 1037 | while queue: 1038 | vals = [] 1039 | for _ in range(len(queue)): 1040 | node = queue.popleft() 1041 | vals.append(node.val) 1042 | if node.left: queue.append(node.left) 1043 | if node.right: queue.append(node.right) 1044 | ans.append(vals) 1045 | return ans 1046 | 1047 | 1048 | """剑指 Offer 33. 二叉搜索树的后序遍历序列 (中等) 1049 | 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则 1050 | 返回 false。假设输入的数组的任意两个数字都互不相同。参考以下这颗二叉搜索树: 1051 | 5 1052 | / \ 1053 | 2 6 1054 | / \ 1055 | 1 3 1056 | 1057 | 示例 1: 1058 | 输入: [1,6,3,2,5] 1059 | 输出: false 1060 | 1061 | 示例 2: 1062 | 输入: [1,3,2,6,5] 1063 | 输出: true 1064 | 1065 | 提示:数组长度 <= 1000""" 1066 | 1067 | def verifyPostorder(self, postorder: List[int]) -> bool: 1068 | upper = inf 1069 | stack = [] 1070 | for x in reversed(postorder): 1071 | if upper < x: return False 1072 | while stack and stack[-1] > x: upper = stack.pop() 1073 | stack.append(x) 1074 | return True 1075 | 1076 | 1077 | """剑指 Offer 39. 数组中出现次数超过一半的数字 (简单) 1078 | 数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。 你可以假设数组是非空的, 1079 | 并且给定的数组总是存在多数元素。 1080 | 1081 | 示例 1: 1082 | 输入: [1, 2, 3, 2, 2, 2, 5, 4, 2] 1083 | 输出: 2 1084 | 1085 | 限制:1 <= 数组长度 <= 50000 1086 | 注意:本题与主站 169 题相同:https://leetcode-cn.com/problems/majority-element/""" 1087 | 1088 | def majorityElement(self, nums: List[int]) -> int: 1089 | ans = vote = 0 1090 | for x in nums: 1091 | if vote == 0: ans = x 1092 | if x == ans: vote += 1 1093 | else: vote -= 1 1094 | return ans 1095 | 1096 | 1097 | """剑指 Offer 40. 最小的k个数 (简单) 1098 | 输入整数数组 arr ,找出其中最小的 k 个数。例如,输入4、5、1、6、2、7、3、8 1099 | 这8个数字,则最小的4个数字是1、2、3、4。 1100 | 1101 | 示例 1: 1102 | 输入:arr = [3,2,1], k = 2 1103 | 输出:[1,2] 或者 [2,1] 1104 | 1105 | 示例 2: 1106 | 输入:arr = [0,1,2,1], k = 1 1107 | 输出:[0] 1108 | 1109 | 限制: 1110 | * 0 <= k <= arr.length <= 10000 1111 | * 0 <= arr[i] <= 10000""" 1112 | 1113 | def getLeastNumbers(self, arr: List[int], k: int) -> List[int]: 1114 | shuffle(arr) 1115 | 1116 | def part(lo, hi): 1117 | """Return arr[lo:hi]""" 1118 | i, j = lo+1, hi-1 1119 | while i <= j: 1120 | if arr[i] < arr[lo]: i += 1 1121 | elif arr[j] > arr[lo]: j -= 1 1122 | else: 1123 | arr[i], arr[j] = arr[j], arr[i] 1124 | i += 1 1125 | j -= 1 1126 | arr[lo], arr[j] = arr[j], arr[lo] 1127 | return j 1128 | 1129 | lo, hi = 0, len(arr) 1130 | while lo < hi: 1131 | mid = part(lo, hi) 1132 | if mid+1 < k: lo = mid+1 1133 | elif mid+1 == k: break 1134 | else: hi = mid 1135 | return arr[:k] 1136 | 1137 | 1138 | """剑指 Offer 42. 连续子数组的最大和 (简单) 1139 | 输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求 1140 | 时间复杂度为O(n)。 1141 | 1142 | 示例1: 1143 | 输入: nums = [-2,1,-3,4,-1,2,1,-5,4] 1144 | 输出: 6 1145 | 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 1146 | 1147 | 提示: 1148 | * 1 <= arr.length <= 10^5 1149 | * -100 <= arr[i] <= 100 1150 | 1151 | 注意:本题与主站 53 题相同:https://leetcode-cn.com/problems/maximum-subarray/""" 1152 | 1153 | def maxSubArray(self, nums: List[int]) -> int: 1154 | ans = -inf 1155 | val = 0 1156 | for x in nums: 1157 | val = max(val, 0) + x 1158 | ans = max(ans, val) 1159 | return ans 1160 | 1161 | 1162 | """剑指 Offer 45. 把数组排成最小的数 (中等) 1163 | 输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。 1164 | 1165 | 示例 1: 1166 | 输入: [10,2] 1167 | 输出: "102" 1168 | 1169 | 示例 2: 1170 | 输入: [3,30,34,5,9] 1171 | 输出: "3033459" 1172 | 1173 | 提示: 0 < nums.length <= 100 1174 | 1175 | 说明: 1176 | * 输出结果可能非常大,所以你需要返回一个字符串而不是整数 1177 | * 拼接起来的数字可能会有前导 0,最后结果不需要去掉前导 0""" 1178 | 1179 | def minNumber(self, nums: List[int]) -> str: 1180 | 1181 | def cmp(s1, s2): 1182 | if s1+s2 < s2+s1: return -1 1183 | elif s1+s2 == s2+s1: return 0 1184 | else: return 1 1185 | 1186 | return "".join(sorted(map(str, nums), key=cmp_to_key(cmp))) 1187 | 1188 | 1189 | """剑指 Offer 50. 第一个只出现一次的字符 (简单) 1190 | 在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。 1191 | 1192 | 示例 1: 1193 | 输入:s = "abaccdeff" 1194 | 输出:'b' 1195 | 1196 | 示例 2: 1197 | 输入:s = "" 1198 | 输出:' ' 1199 | 1200 | 限制:0 <= s 的长度 <= 50000""" 1201 | 1202 | def firstUniqChar(self, s: str) -> str: 1203 | freq = Counter(s) 1204 | return next((ch for ch in s if freq[ch] == 1), ' ') 1205 | 1206 | 1207 | """剑指 Offer 51. 数组中的逆序对 (困难) 1208 | 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数 1209 | 组,求出这个数组中的逆序对的总数。 1210 | 1211 | 示例 1: 1212 | 输入: [7,5,6,4] 1213 | 输出: 5 1214 | 1215 | 限制:0 <= 数组长度 <= 50000""" 1216 | 1217 | def reversePairs(self, nums: List[int]) -> int: 1218 | 1219 | def fn(nums, aux, lo, hi): 1220 | """Return inversions of nums[lo:hi].""" 1221 | if lo+1 >= hi: return 0 1222 | mid = lo + hi >> 1 1223 | left = fn(aux, nums, lo, mid) 1224 | right = fn(aux, nums, mid, hi) 1225 | split = 0 1226 | i, j = lo, mid 1227 | for k in range(lo, hi): 1228 | if j >= hi or i < mid and aux[i] <= aux[j]: 1229 | nums[k] = aux[i] 1230 | i += 1 1231 | else: 1232 | nums[k] = aux[j] 1233 | j += 1 1234 | split += mid - i 1235 | return left + split + right 1236 | 1237 | return fn(nums, nums.copy(), 0, len(nums)) 1238 | 1239 | 1240 | """剑指 Offer 52. 两个链表的第一个公共节点 (简单) 1241 | 输入两个链表,找出它们的第一个公共节点。 1242 | 1243 | 示例 1: 1244 | 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 1245 | 输出:Reference of the node with value = 8 1246 | 输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起, 1247 | 链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 1248 | 个节点;在 B 中,相交节点前有 3 个节点。 1249 | 1250 | 示例 2: 1251 | 输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 1252 | 输出:Reference of the node with value = 2 1253 | 输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起, 1254 | 链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点; 1255 | 在 B 中,相交节点前有 1 个节点。 1256 | 1257 | 示例 3: 1258 | 输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 1259 | 输出:null 1260 | 输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不 1261 | 相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。解释: 1262 | 这两个链表不相交,因此返回 null。 1263 | 1264 | 注意: 1265 | * 如果两个链表没有交点,返回 null. 1266 | * 在返回结果后,两个链表仍须保持原有的结构。 1267 | * 可假定整个链表结构中没有循环。 1268 | * 程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。 1269 | 本题与主站 160 题相同:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/""" 1270 | 1271 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: 1272 | nodeA, nodeB = headA, headB 1273 | while nodeA != nodeB: 1274 | nodeA = nodeA.next if nodeA else headB 1275 | nodeB = nodeB.next if nodeB else headA 1276 | return nodeA 1277 | 1278 | 1279 | """剑指 Offer 53 - I. 在排序数组中查找数字 I (简单) 1280 | 统计一个数字在排序数组中出现的次数。 1281 | 1282 | 示例 1: 1283 | 输入: nums = [5,7,7,8,8,10], target = 8 1284 | 输出: 2 1285 | 1286 | 示例 2: 1287 | 输入: nums = [5,7,7,8,8,10], target = 6 1288 | 输出: 0 1289 | 1290 | 提示: 1291 | * 0 <= nums.length <= 10^5 1292 | * -10^9 <= nums[i] <= 10^9 1293 | * nums 是一个非递减数组 1294 | * -10^9 <= target <= 10^9 1295 | 1296 | 注意:本题与主站 34 题相同(仅返回值不同): 1297 | https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/""" 1298 | 1299 | def search(self, nums: List[int], target: int) -> int: 1300 | lo = bisect_left(nums, target) 1301 | if lo < len(nums) and nums[lo] == target: return bisect_right(nums, target) - lo 1302 | return 0 1303 | 1304 | 1305 | """剑指 Offer 53 - II. 0~n-1中缺失的数字 (简单) 1306 | 一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。 1307 | 在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。 1308 | 1309 | 示例 1: 1310 | 输入: [0,1,3] 1311 | 输出: 2 1312 | 1313 | 示例 2: 1314 | 输入: [0,1,2,3,4,5,6,7,9] 1315 | 输出: 8 1316 | 1317 | 限制:1 <= 数组长度 <= 10000""" 1318 | 1319 | def missingNumber(self, nums: List[int]) -> int: 1320 | ans = 0 1321 | for x in nums: ans ^= x 1322 | for x in range(len(nums)+1): ans ^= x 1323 | return ans 1324 | 1325 | 1326 | """剑指 Offer 54. 二叉搜索树的第k大节点 (简单) 1327 | 给定一棵二叉搜索树,请找出其中第k大的节点。 1328 | 1329 | 示例 1: 1330 | 输入: root = [3,1,4,null,2], k = 1 1331 | 3 1332 | / \ 1333 | 1 4 1334 | \ 1335 | 2 1336 | 输出: 4 1337 | 1338 | 示例 2: 1339 | 输入: root = [5,3,6,2,4,null,null,1], k = 3 1340 | 5 1341 | / \ 1342 | 3 6 1343 | / \ 1344 | 2 4 1345 | / 1346 | 1 1347 | 输出: 4 1348 | 1349 | 限制:1 ≤ k ≤ 二叉搜索树元素个数""" 1350 | 1351 | def kthLargest(self, root: TreeNode, k: int) -> int: 1352 | node = root 1353 | stack = [] 1354 | while node or stack: 1355 | if node: 1356 | stack.append(node) 1357 | node = node.right 1358 | else: 1359 | node = stack.pop() 1360 | k -= 1 1361 | if k == 0: return node.val 1362 | node = node.left 1363 | 1364 | 1365 | """剑指 Offer 55 - I. 二叉树的深度 (简单) 1366 | 输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树 1367 | 的一条路径,最长路径的长度为树的深度。 1368 | 1369 | 例如: 1370 | 给定二叉树 [3,9,20,null,null,15,7], 1371 | 3 1372 | / \ 1373 | 9 20 1374 | / \ 1375 | 15 7 1376 | 返回它的最大深度 3 。 1377 | 1378 | 提示:节点总数 <= 10000 1379 | 注意:本题与主站 104 题相同:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/""" 1380 | 1381 | def maxDepth(self, root: TreeNode) -> int: 1382 | ans = 0 1383 | if root: 1384 | stack = [(root, 1)] 1385 | while stack: 1386 | node, depth = stack.pop() 1387 | ans = max(ans, depth) 1388 | if node.left: stack.append((node.left, depth+1)) 1389 | if node.right: stack.append((node.right, depth+1)) 1390 | return ans 1391 | 1392 | 1393 | """剑指 Offer 55 - II. 平衡二叉树 (简单) 1394 | 输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相 1395 | 差不超过1,那么它就是一棵平衡二叉树。 1396 | 1397 | 示例 1: 1398 | 给定二叉树 [3,9,20,null,null,15,7] 1399 | 3 1400 | / \ 1401 | 9 20 1402 | / \ 1403 | 15 7 1404 | 返回 true 。 1405 | 1406 | 示例 2: 1407 | 给定二叉树 [1,2,2,3,3,null,null,4,4] 1408 | 1409 | 1 1410 | / \ 1411 | 2 2 1412 | / \ 1413 | 3 3 1414 | / \ 1415 | 4 4 1416 | 返回 false 。 1417 | 1418 | 限制:0 <= 树的结点个数 <= 10000 1419 | 注意:本题与主站 110 题相同:https://leetcode-cn.com/problems/balanced-binary-tree/""" 1420 | 1421 | def isBalanced(self, root: TreeNode) -> bool: 1422 | stack = [] 1423 | height = {None: 0} 1424 | prev, node = None, root 1425 | while node or stack: 1426 | if node: 1427 | stack.append(node) 1428 | node = node.left 1429 | else: 1430 | node = stack[-1] 1431 | if node.right and prev != node.right: node = node.right 1432 | else: 1433 | if abs(height[node.left] - height[node.right]) > 1: return False 1434 | height[node] = 1 + max(height[node.left], height[node.right]) 1435 | stack.pop() 1436 | prev = node 1437 | node = None 1438 | return True 1439 | 1440 | 1441 | """剑指 Offer 56 - II. 数组中数字出现的次数 II (中等) 1442 | 在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一 1443 | 次的数字。 1444 | 1445 | 示例 1: 1446 | 输入:nums = [3,4,3,3] 1447 | 输出:4 1448 | 1449 | 示例 2: 1450 | 输入:nums = [9,1,7,9,7,9,7] 1451 | 输出:1 1452 | 1453 | 限制: 1454 | * 1 <= nums.length <= 10000 1455 | * 1 <= nums[i] < 2^31""" 1456 | 1457 | def singleNumber(self, nums: List[int]) -> int: 1458 | one = two = 0 1459 | for x in nums: 1460 | two |= one & x 1461 | one ^= x 1462 | common = one & two 1463 | one &= ~common 1464 | two &= ~common 1465 | return one 1466 | 1467 | 1468 | """剑指 Offer 57. 和为s的两个数字 (简单) 1469 | 输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s。如果有多对数 1470 | 字的和等于s,则输出任意一对即可。 1471 | 1472 | 示例 1: 1473 | 输入:nums = [2,7,11,15], target = 9 1474 | 输出:[2,7] 或者 [7,2] 1475 | 1476 | 示例 2: 1477 | 输入:nums = [10,26,30,31,47,60], target = 40 1478 | 输出:[10,30] 或者 [30,10] 1479 | 1480 | 限制: 1481 | * 1 <= nums.length <= 10^5 1482 | * 1 <= nums[i] <= 10^6""" 1483 | 1484 | def twoSum(self, nums: List[int], target: int) -> List[int]: 1485 | lo, hi = 0, len(nums)-1 1486 | while lo < hi: 1487 | if nums[lo] + nums[hi] < target: lo += 1 1488 | elif nums[lo] + nums[hi] == target: return [nums[lo], nums[hi]] 1489 | else: hi -= 1 1490 | 1491 | 1492 | """剑指 Offer 57 - II. 和为s的连续正数序列 (简单) 1493 | 输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。 1494 | 序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。 1495 | 1496 | 示例 1: 1497 | 输入:target = 9 1498 | 输出:[[2,3,4],[4,5]] 1499 | 1500 | 示例 2: 1501 | 输入:target = 15 1502 | 输出:[[1,2,3,4,5],[4,5,6],[7,8]] 1503 | 1504 | 限制:1 <= target <= 10^5""" 1505 | 1506 | def findContinuousSequence(self, target: int) -> List[List[int]]: 1507 | ans = [] 1508 | prefix = 0 1509 | for x in range(1, int((-1+sqrt(8*target-1))//2)+1): 1510 | prefix += x 1511 | if (target-prefix) % (x+1) == 0: 1512 | v = (target-prefix)//(x+1) 1513 | ans.append(list(range(v, v+x+1))) 1514 | return ans[::-1] 1515 | 1516 | 1517 | """剑指 Offer 58 - I. 翻转单词顺序 (简单) 1518 | 输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通 1519 | 字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。 1520 | 1521 | 示例 1: 1522 | 输入: "the sky is blue" 1523 | 输出: "blue is sky the" 1524 | 1525 | 示例 2: 1526 | 输入: " hello world! " 1527 | 输出: "world! hello" 1528 | 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 1529 | 1530 | 示例 3: 1531 | 输入: "a good example" 1532 | 输出: "example good a" 1533 | 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 1534 | 1535 | 说明: 1536 | * 无空格字符构成一个单词。 1537 | * 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 1538 | * 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 1539 | 1540 | 注意:本题与主站 151 题相同:https://leetcode-cn.com/problems/reverse-words-in-a-string/ 1541 | 注意:此题对比原题有改动""" 1542 | 1543 | def reverseWords(self, s: str) -> str: 1544 | return ' '.join(reversed(s.split())) 1545 | 1546 | 1547 | """剑指 Offer 58 - II. 左旋转字符串 (简单) 1548 | 字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左 1549 | 旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果 1550 | "cdefgab"。 1551 | 1552 | 示例 1: 1553 | 输入: s = "abcdefg", k = 2 1554 | 输出: "cdefgab" 1555 | 1556 | 示例 2: 1557 | 输入: s = "lrloseumgh", k = 6 1558 | 输出: "umghlrlose" 1559 | 1560 | 限制:1 <= k < s.length <= 10000""" 1561 | 1562 | def reverseLeftWords(self, s: str, n: int) -> str: 1563 | return s[n:] + s[:n] 1564 | 1565 | 1566 | """剑指 Offer 61. 扑克牌中的顺子 (简单) 1567 | 从若干副扑克牌中随机抽 5 张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数 1568 | 字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。 1569 | 1570 | 示例 1: 1571 | 输入: [1,2,3,4,5] 1572 | 输出: True 1573 | 1574 | 示例 2: 1575 | 输入: [0,0,1,2,5] 1576 | 输出: True 1577 | 1578 | 限制: 1579 | * 数组长度为 5 1580 | * 数组的数取值为 [0, 13] .""" 1581 | 1582 | def isStraight(self, nums: List[int]) -> bool: 1583 | seen = set() 1584 | lo, hi = inf, 0 1585 | for x in nums: 1586 | if x: 1587 | if x in seen: return False 1588 | seen.add(x) 1589 | lo = min(lo, x) 1590 | hi = max(hi, x) 1591 | return hi - lo < 5 1592 | 1593 | 1594 | """剑指 Offer 60. n个骰子的点数 (中等) 1595 | 把n个骰子扔在地上,所有骰子朝上一面的点数之和为s。输入n,打印出s的所有可能的值出现的概 1596 | 率。你需要用一个浮点数数组返回答案,其中第 i 个元素代表这 n 个骰子所能掷出的点数集合中 1597 | 第 i 小的那个的概率。 1598 | 1599 | 示例 1: 1600 | 输入: 1 1601 | 输出: [0.16667,0.16667,0.16667,0.16667,0.16667,0.16667] 1602 | 1603 | 示例 2: 1604 | 输入: 2 1605 | 输出: [0.02778,0.05556,0.08333,0.11111,0.13889,0.16667,0.13889,0.11111,0.08333,0.05556,0.02778] 1606 | 1607 | 限制:1 <= n <= 11""" 1608 | 1609 | def dicesProbability(self, n: int) -> List[float]: 1610 | 1611 | @cache 1612 | def fn(n, x): 1613 | """Return probability of getting x with n tosses.""" 1614 | if not n <= x <= 6*n: return 0 1615 | if n == 1: return 1/6 1616 | return 1/6*sum(fn(n-1, x-xx) for xx in range(1, 7)) 1617 | 1618 | return [fn(n, x) for x in range(n, 6*n+1)] 1619 | 1620 | 1621 | """剑指 Offer 62. 圆圈中最后剩下的数字 (简单) 1622 | 0,1,···,n-1这n个数字排成一个圆圈,从数字0开始,每次从这个圆圈里删除第m个数字 1623 | (删除后从下一个数字开始计数)。求出这个圆圈里剩下的最后一个数字。例如, 1624 | 0、1、2、3、4这5个数字组成一个圆圈,从数字0开始每次删除第3个数字,则删除的前4个数 1625 | 字依次是2、0、4、1,因此最后剩下的数字是3。 1626 | 1627 | 示例 1: 1628 | 输入: n = 5, m = 3 1629 | 输出: 3 1630 | 1631 | 示例 2: 1632 | 输入: n = 10, m = 17 1633 | 输出: 2 1634 | 1635 | 限制: 1636 | * 1 <= n <= 10^5 1637 | * 1 <= m <= 10^6""" 1638 | 1639 | def lastRemaining(self, n: int, m: int) -> int: 1640 | ans = 0 1641 | for x in range(2, n+1): ans = (ans + m) % x 1642 | return ans 1643 | 1644 | 1645 | """剑指 Offer 65. 不用加减乘除做加法 (简单) 1646 | 写一个函数,求两个整数之和,要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。 1647 | 1648 | 示例: 1649 | 输入: a = 1, b = 1 1650 | 输出: 2 1651 | 1652 | 提示: 1653 | * a, b 均可能是负数或 0 1654 | * 结果不会溢出 32 位整数""" 1655 | 1656 | def add(self, a: int, b: int) -> int: 1657 | mask = 0xffffffff 1658 | while b & mask: a, b = a^b, (a&b) << 1 1659 | return a&mask if b > mask else a 1660 | 1661 | 1662 | """剑指 Offer 66. 构建乘积数组 (中等) 1663 | 给定一个数组 A[0,1,…,n-1],请构建一个数组 B[0,1,…,n-1],其中 B[i] 的值是数组 A 1664 | 中除了下标 i 以外的元素的积, 即 B[i]=A[0]×A[1]×…×A[i-1]×A[i+1]×…×A[n-1]。不能 1665 | 使用除法。 1666 | 1667 | 示例: 1668 | 输入: [1,2,3,4,5] 1669 | 输出: [120,60,40,30,24] 1670 | 1671 | 提示: 1672 | * 所有元素乘积之和不会溢出 32 位整数 1673 | * a.length <= 100000""" 1674 | 1675 | def constructArr(self, a: List[int]) -> List[int]: 1676 | ans = [1] * len(a) 1677 | prefix = suffix = 1 1678 | for i, x in enumerate(a): 1679 | ans[i] *= prefix 1680 | ans[~i] *= suffix 1681 | prefix *= a[i] 1682 | suffix *= a[~i] 1683 | return ans 1684 | 1685 | 1686 | """剑指 Offer 68 - I. 二叉搜索树的最近公共祖先 (简单) 1687 | 给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为: 1688 | “对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 1689 | 的深度尽可能大(一个节点也可以是它自己的祖先)。”例如,给定如下二叉搜索树: 1690 | root = [6,2,8,0,4,7,9,null,null,3,5] 1691 | 1692 | 示例 1: 1693 | 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 1694 | 输出: 6 1695 | 解释: 节点 2 和节点 8 的最近公共祖先是 6。 1696 | 1697 | 示例 2: 1698 | 输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 1699 | 输出: 2 1700 | 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。 1701 | 1702 | 说明: 1703 | * 所有节点的值都是唯一的。 1704 | * p、q 为不同节点且均存在于给定的二叉搜索树中。 1705 | 注意:本题与主站 235 题相同: 1706 | https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/""" 1707 | 1708 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 1709 | if p.val > q.val: p, q = q, p 1710 | node = root 1711 | while node: 1712 | if node.val < p.val: node = node.right 1713 | elif p.val <= node.val <= q.val: return node 1714 | else: node = node.left 1715 | 1716 | 1717 | """剑指 Offer 68 - II. 二叉树的最近公共祖先 (简单) 1718 | 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。百度百科中最近公共祖先的定义为: 1719 | “对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 1720 | x 的深度尽可能大(一个节点也可以是它自己的祖先)。”例如,给定如下二叉树: 1721 | root = [3,5,1,6,2,0,8,null,null,7,4] 1722 | 1723 | 示例 1: 1724 | 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 1725 | 输出: 3 1726 | 解释: 节点 5 和节点 1 的最近公共祖先是节点 3。 1727 | 1728 | 示例 2: 1729 | 输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 1730 | 输出: 5 1731 | 解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。 1732 | 1733 | 说明: 1734 | * 所有节点的值都是唯一的。 1735 | * p、q 为不同节点且均存在于给定的二叉树中。 1736 | 注意:本题与主站 236 题相同: 1737 | https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/""" 1738 | 1739 | def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode: 1740 | if not root or root in (p, q): return root 1741 | left, right = self.lowestCommonAncestor(root.left, p, q), self.lowestCommonAncestor(root.right, p, q) 1742 | return root if left and right else left or right 1743 | 1744 | 1745 | """meituan-001. 小美的用户名 (简单) 1746 | 小美是美团的前端工程师,为了防止系统被恶意攻击,小美必须要在用户输入用户名之前做一个合法性 1747 | 检查,一个合法的用户名必须满足以下几个要求: 1748 | * 用户名的首字符必须是大写或者小写字母。 1749 | * 用户名只能包含大小写字母,数字。 1750 | * 用户名需要包含至少一个字母和一个数字。 1751 | 如果用户名合法,请输出 "Accept",反之输出 "Wrong"。 1752 | 1753 | 格式: 1754 | 输入: 1755 | - 输入第一行包含一个正整数 T,表示需要检验的用户名数量。 1756 | - 接下来有 T 行,每行一个字符串 s,表示输入的用户名。 1757 | 输出: 1758 | - 对于每一个输入的用户名 s,请输出一行,即按题目要求输出一个字符串。 1759 | 1760 | 示例: 1761 | 输入:5 1762 | Ooook 1763 | Hhhh666 1764 | ABCD 1765 | Meituan 1766 | 6666 1767 | 输出:Wrong 1768 | Accept 1769 | Wrong 1770 | Wrong 1771 | Wrong 1772 | 提示: 1773 | * 1 <= T <= 100 1774 | * s 的长度不超过 20 1775 | * 请注意,本题需要自行编写「标准输入」和「标准输出」逻辑,以及自行 import/include 需要的 1776 | library。了解书写规则""" 1777 | 1778 | def meituan_001(self): 1779 | n = int(input()) 1780 | for _ in range(n): 1781 | name = input() 1782 | if name.isalnum() and name[0].isalpha() and any(x.isdigit() for x in name): print("Accept") 1783 | else: print("Wrong") 1784 | 1785 | 1786 | """meituan-002. 小美的仓库整理 (中等) 1787 | 小美是美团仓库的管理员,她会根据单据的要求按顺序取出仓库中的货物,每取出一件货物后会把剩余 1788 | 货物重新堆放,使得自己方便查找。已知货物入库的时候是按顺序堆放在一起的。如果小美取出其中一 1789 | 件货物,则会把货物所在的一堆物品以取出的货物为界分成两堆,这样可以保证货物局部的顺序不变。 1790 | 已知货物最初是按 1~n 的顺序堆放的,每件货物的重量为 w[i] ,小美会根据单据依次不放回的取出 1791 | 货物。请问根据上述操作,小美每取出一件货物之后,重量和最大的一堆货物重量是多少? 1792 | 1793 | 格式: 1794 | 输入: 1795 | - 输入第一行包含一个正整数 n ,表示货物的数量。 1796 | - 输入第二行包含 n 个正整数,表示 1~n 号货物的重量 w[i] 。 1797 | - 输入第三行有 n 个数,表示小美按顺序取出的货物的编号,也就是一个 1~n 的全排列。 1798 | 输出: 1799 | - 输出包含 n 行,每行一个整数,表示每取出一件货物以后,对于重量和最大的一堆货物,其重量和为多少。 1800 | 1801 | 示例: 1802 | 输入: 1803 | 5 1804 | 3 2 4 4 5 1805 | 4 3 5 2 1 1806 | 输出: 1807 | 9 1808 | 5 1809 | 5 1810 | 3 1811 | 0 1812 | 解释: 1813 | 原本的状态是 {{3,2,4,4,5}} ,取出 4 号货物后,得到 {{3,2,4},{5}} ,第一堆货物的和是 9 , 1814 | 然后取出 3 号货物得到 {{3,2}{5}} ,此时第一堆和第二堆的和都是 5 ,以此类推。 1815 | 1816 | 提示: 1817 | * 1 <= n <= 50000 1818 | * 1 <= w[i] <= 100 1819 | * 请注意,本题需要自行编写「标准输入」和「标准输出」逻辑,以及自行 import/include 需要的 1820 | library。了解书写规则""" 1821 | 1822 | def meituan_002(self): 1823 | n = int(input()) 1824 | prefix = [0] 1825 | for x in input().split(): prefix.append(prefix[-1] + int(x)) 1826 | ans = [] 1827 | most = 0 1828 | seen = [0]*n 1829 | lower = list(range(n)) 1830 | upper = list(range(n)) 1831 | for i in reversed(input().split()): 1832 | ans.append(most) 1833 | i = int(i) - 1 1834 | seen[i] = 1 1835 | if i and seen[i-1]: lower[i] = lower[i-1] 1836 | if i+1 < n and seen[i+1]: upper[i] = upper[i+1] 1837 | upper[lower[i]] = upper[i] 1838 | lower[upper[i]] = lower[i] 1839 | most = max(most, prefix[upper[i]+1] - prefix[lower[i]]) 1840 | for x in reversed(ans): print(x) 1841 | 1842 | 1843 | """meituan-003. 小美的跑腿代购 (简单) 1844 | 小美的一个兼职是美团的一名跑腿代购员,她有 n 个订单可以接,订单编号是 1~n ,但是因 1845 | 为订单的时效性,他只能选择其中 m 个订单接取,精明的小美当然希望自己总的获利是最大的, 1846 | 已知,一份订单会提供以下信息,跑腿价格 v ,商品重量 w kg,商品每重 1kg ,代购费用 1847 | 要加 2 元,而一份订单可以赚到的钱是跑腿价格和重量加价之和。小美可是开兰博基尼送货的 1848 | 人,所以自然不会在意自己会累这种事情。请问小美应该选择哪些订单,使得自己获得的钱最多。 1849 | 请你按照选择的订单编号的从小到大顺序,如果存在多种方案,输出订单编号字典序较小的方案。 1850 | 1851 | 格式: 1852 | 输入: 1853 | - 输入第一行包含两个正整数 n,m,表示订单的数量和小美可以接的订单数量。 1854 | - 接下来有 n 行,第 i 行表示 i-1 号订单的信息。每行有两个正整数 v 和 w ,表示一个 1855 | 订单的跑腿价格和商品重量。 1856 | 输出: 1857 | - 输出包含 m 个 1~n 之间的正整数,中间用空格隔开,表示选择的订单编号。 1858 | 1859 | 示例: 1860 | 输入:5 2 1861 | 5 10 1862 | 8 9 1863 | 1 4 1864 | 7 9 1865 | 6 10 1866 | 输出:2 5 1867 | 1868 | 提示: 1869 | * 1 <= n, m <= 10000 1870 | * 1 <= v, w <= 1000 1871 | * 请注意,本题需要自行编写「标准输入」和「标准输出」逻辑,以及自行 import/include 1872 | 需要的 library。了解书写规则""" 1873 | 1874 | def meituan_003(self): 1875 | """Print Xiaomei's order number.""" 1876 | n, m = map(int, input().split()) 1877 | nums = [] 1878 | for _ in range(n): 1879 | v, w = map(int, input().split()) 1880 | nums.append(v + 2*w) 1881 | threshold = sorted(nums)[-m] 1882 | equal = m - sum(x > threshold for x in nums) 1883 | for i, x in enumerate(nums): 1884 | if x > threshold or x == threshold and equal > 0: 1885 | if x == threshold: equal -= 1 1886 | print(i+1, end=" ") 1887 | -------------------------------------------------------------------------------- /leetcode.go: -------------------------------------------------------------------------------- 1 | /*1. Two Sum (Easy) 2 | Given an array of integers nums and an integer target, return indices of the two 3 | numbers such that they add up to target. You may assume that each input would 4 | have exactly one solution, and you may not use the same element twice. You can 5 | return the answer in any order. 6 | 7 | Example 1: 8 | Input: nums = [2,7,11,15], target = 9 9 | Output: [0,1] 10 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 11 | 12 | Example 2: 13 | Input: nums = [3,2,4], target = 6 14 | Output: [1,2] 15 | 16 | Example 3: 17 | Input: nums = [3,3], target = 6 18 | Output: [0,1] 19 | 20 | Constraints: 21 | * 2 <= nums.length <= 10^4 22 | * -10^9 <= nums[i] <= 10^9 23 | * -10^9 <= target <= 10^9 24 | * Only one valid answer exists.*/ 25 | 26 | func twoSum(nums []int, target int) []int { 27 | seen := make(map[int]int) 28 | for i, x := range nums { 29 | j, found := seen[target-x] 30 | if found { 31 | return []int{j, i} 32 | } 33 | seen[x] = i 34 | } 35 | return []int{} 36 | } 37 | 38 | 39 | /*9. Palindrome Number (Easy) 40 | Given an integer x, return true if x is a palindrome, and false otherwise. 41 | 42 | Example 1: 43 | Input: x = 121 44 | Output: true 45 | Explanation: 121 reads as 121 from left to right and from right to left. 46 | 47 | Example 2: 48 | Input: x = -121 49 | Output: false 50 | Explanation: From left to right, it reads -121. From right to left, it becomes 51 | 121-. Therefore it is not a palindrome. 52 | 53 | Example 3: 54 | Input: x = 10 55 | Output: false 56 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 57 | 58 | Constraints: -2^31 <= x <= 2^31 - 1 59 | 60 | Follow up: Could you solve it without converting the integer to a string?*/ 61 | 62 | func isPalindrome(x int) bool { 63 | r := 0 64 | for xx := x; xx > 0; xx /= 10 { 65 | r = 10*r + xx % 10 66 | } 67 | return x == r 68 | } 69 | 70 | 71 | /*13. Roman to Integer (Easy) 72 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and 73 | M. 74 | Symbol Value 75 | I 1 76 | V 5 77 | X 10 78 | L 50 79 | C 100 80 | D 500 81 | M 1000 82 | For example, 2 is written as II in Roman numeral, just two ones added together. 83 | 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, 84 | which is XX + V + II. Roman numerals are usually written largest to smallest 85 | from left to right. However, the numeral for four is not IIII. Instead, the 86 | number four is written as IV. Because the one is before the five we subtract it 87 | making four. The same principle applies to the number nine, which is written as 88 | IX. There are six instances where subtraction is used: 89 | * I can be placed before V (5) and X (10) to make 4 and 9. 90 | * X can be placed before L (50) and C (100) to make 40 and 90. 91 | * C can be placed before D (500) and M (1000) to make 400 and 900. 92 | Given a roman numeral, convert it to an integer. 93 | 94 | Example 1: 95 | Input: s = "III" 96 | Output: 3 97 | Explanation: III = 3. 98 | 99 | Example 2: 100 | Input: s = "LVIII" 101 | Output: 58 102 | Explanation: L = 50, V= 5, III = 3. 103 | 104 | Example 3: 105 | Input: s = "MCMXCIV" 106 | Output: 1994 107 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 108 | 109 | Constraints: 110 | * 1 <= s.length <= 15 111 | * s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). 112 | * It is guaranteed that s is a valid roman numeral in the range [1, 3999].*/ 113 | 114 | func romanToInt(s string) int { 115 | symbol := map[rune]int { 116 | 'I' : 1, 117 | 'V' : 5, 118 | 'X' : 10, 119 | 'L' : 50, 120 | 'C' : 100, 121 | 'D' : 500, 122 | 'M' : 1000, 123 | } 124 | ans := 0 125 | for i, ch := range s { 126 | if i+1 < len(s) && symbol[ch] < symbol[rune(s[i+1])] { 127 | ans -= symbol[ch] 128 | } else { 129 | ans += symbol[ch] 130 | } 131 | } 132 | return ans 133 | } 134 | 135 | 136 | /*14. Longest Common Prefix (Easy) 137 | Write a function to find the longest common prefix string amongst an array of 138 | strings. If there is no common prefix, return an empty string "". 139 | 140 | Example 1: 141 | Input: strs = ["flower","flow","flight"] 142 | Output: "fl" 143 | 144 | Example 2: 145 | Input: strs = ["dog","racecar","car"] 146 | Output: "" 147 | Explanation: There is no common prefix among the input strings. 148 | 149 | Constraints: 150 | * 1 <= strs.length <= 200 151 | * 0 <= strs[i].length <= 200 152 | * strs[i] consists of only lowercase English letters if it is non-empty.*/ 153 | 154 | func longestCommonPrefix(strs []string) string { 155 | for j, _ := range strs[0] { 156 | for i := 1; i < len(strs); i++ { 157 | if j == len(strs[i]) || strs[0][j] != strs[i][j] { 158 | return strs[0][:j] 159 | } 160 | } 161 | } 162 | return strs[0] 163 | } 164 | 165 | 166 | /*20. Valid Parentheses (Easy) 167 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', 168 | determine if the input string is valid. An input string is valid if: 169 | * Open brackets must be closed by the same type of brackets. 170 | * Open brackets must be closed in the correct order. 171 | * Every close bracket has a corresponding open bracket of the same type. 172 | 173 | Example 1: 174 | Input: s = "()" 175 | Output: true 176 | 177 | Example 2: 178 | Input: s = "()[]{}" 179 | Output: true 180 | 181 | Example 3: 182 | Input: s = "(]" 183 | Output: false 184 | 185 | Example 4: 186 | Input: s = "([])" 187 | Output: true 188 | 189 | Constraints: 190 | * 1 <= s.length <= 10^4 191 | * s consists of parentheses only '()[]{}'.*/ 192 | 193 | func isValid(s string) bool { 194 | pair := map[rune]rune { 195 | ')' : '(', 196 | ']' : '[', 197 | '}' : '{', 198 | } 199 | stack := []rune{} 200 | for _, ch := range s { 201 | if strings.ContainsRune("([{", ch) { 202 | stack = append(stack, ch) 203 | } else { 204 | sz := len(stack) 205 | if sz == 0 || stack[sz-1] != pair[ch] { 206 | return false 207 | } 208 | stack = stack[:sz-1] 209 | } 210 | } 211 | return len(stack) == 0 212 | } 213 | 214 | 215 | /*21. Merge Two Sorted Lists (Easy) 216 | You are given the heads of two sorted linked lists list1 and list2. Merge the 217 | two lists into one sorted list. The list should be made by splicing together the 218 | nodes of the first two lists. Return the head of the merged linked list. 219 | 220 | Example 1: 221 | Input: list1 = [1,2,4], list2 = [1,3,4] 222 | Output: [1,1,2,3,4,4] 223 | 224 | Example 2: 225 | Input: list1 = [], list2 = [] 226 | Output: [] 227 | 228 | Example 3: 229 | Input: list1 = [], list2 = [0] 230 | Output: [0] 231 | 232 | Constraints: 233 | * The number of nodes in both lists is in the range [0, 50]. 234 | * -100 <= Node.val <= 100 235 | * Both list1 and list2 are sorted in non-decreasing order.*/ 236 | 237 | func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode { 238 | dummy := &ListNode{} 239 | for node := dummy; list1 != nil || list2 != nil; node = node.Next { 240 | if list1 == nil || list2 != nil && list1.Val >= list2.Val { 241 | node.Next = list2 242 | list2 = list2.Next 243 | } else { 244 | node.Next = list1 245 | list1 = list1.Next 246 | } 247 | } 248 | return dummy.Next 249 | } 250 | 251 | 252 | /*26. Remove Duplicates from Sorted Array (Easy) 253 | Given an integer array nums sorted in non-decreasing order, remove the 254 | duplicates in-place such that each unique element appears only once. The 255 | relative order of the elements should be kept the same. Then return the number 256 | of unique elements in nums. Consider the number of unique elements of nums to be 257 | k, to get accepted, you need to do the following things: 258 | * Change the array nums such that the first k elements of nums contain the 259 | unique elements in the order they were present in nums initially. The 260 | remaining elements of nums are not important as well as the size of nums. 261 | * Return k. 262 | 263 | Custom Judge: 264 | The judge will test your solution with the following code: 265 | int[] nums = [...]; // Input array 266 | int[] expectedNums = [...]; // The expected answer with correct length 267 | 268 | int k = removeDuplicates(nums); // Calls your implementation 269 | 270 | assert k == expectedNums.length; 271 | for (int i = 0; i < k; i++) { 272 | assert nums[i] == expectedNums[i]; 273 | } 274 | If all assertions pass, then your solution will be accepted. 275 | 276 | Example 1: 277 | Input: nums = [1,1,2] 278 | Output: 2, nums = [1,2,_] 279 | Explanation: Your function should return k = 2, with the first two elements of 280 | nums being 1 and 2 respectively. It does not matter what you leave 281 | beyond the returned k (hence they are underscores). 282 | 283 | Example 2: 284 | Input: nums = [0,0,1,1,1,2,2,3,3,4] 285 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] 286 | Explanation: Your function should return k = 5, with the first five elements of 287 | nums being 0, 1, 2, 3, and 4 respectively. It does not matter what 288 | you leave beyond the returned k (hence they are underscores). 289 | 290 | Constraints: 291 | * 1 <= nums.length <= 3 * 10^4 292 | * -100 <= nums[i] <= 100 293 | * nums is sorted in non-decreasing order.*/ 294 | 295 | func removeDuplicates(nums []int) int { 296 | k := 0 297 | for i, x := range nums { 298 | if i == 0 || nums[i-1] < x { 299 | nums[k] = x 300 | k++ 301 | } 302 | } 303 | return k 304 | } 305 | 306 | 307 | /*27. Remove Element (Easy) 308 | Given an integer array nums and an integer val, remove all occurrences of val in 309 | nums in-place. The order of the elements may be changed. Then return the number 310 | of elements in nums which are not equal to val. Consider the number of elements 311 | in nums which are not equal to val be k, to get accepted, you need to do the 312 | following things: 313 | * Change the array nums such that the first k elements of nums contain the 314 | elements which are not equal to val. The remaining elements of nums are not 315 | important as well as the size of nums. 316 | * Return k. 317 | 318 | Custom Judge: 319 | The judge will test your solution with the following code: 320 | int[] nums = [...]; // Input array 321 | int val = ...; // Value to remove 322 | int[] expectedNums = [...]; // The expected answer with correct length. 323 | // It is sorted with no values equaling val. 324 | 325 | int k = removeElement(nums, val); // Calls your implementation 326 | 327 | assert k == expectedNums.length; 328 | sort(nums, 0, k); // Sort the first k elements of nums 329 | for (int i = 0; i < actualLength; i++) { 330 | assert nums[i] == expectedNums[i]; 331 | } 332 | If all assertions pass, then your solution will be accepted. 333 | 334 | Example 1: 335 | Input: nums = [3,2,2,3], val = 3 336 | Output: 2, nums = [2,2,_,_] 337 | Explanation: Your function should return k = 2, with the first two elements of 338 | nums being 2. It does not matter what you leave beyond the returned 339 | k (hence they are underscores). 340 | 341 | Example 2: 342 | Input: nums = [0,1,2,2,3,0,4,2], val = 2 343 | Output: 5, nums = [0,1,4,0,3,_,_,_] 344 | Explanation: Your function should return k = 5, with the first five elements of 345 | nums containing 0, 0, 1, 3, and 4. Note that the five elements can 346 | be returned in any order. It does not matter what you leave beyond 347 | the returned k (hence they are underscores). 348 | 349 | Constraints: 350 | * 0 <= nums.length <= 100 351 | * 0 <= nums[i] <= 50 352 | * 0 <= val <= 100*/ 353 | 354 | func removeElement(nums []int, val int) int { 355 | k := 0 356 | for _, x := range nums { 357 | if x != val { 358 | nums[k] = x 359 | k++ 360 | } 361 | } 362 | return k 363 | } 364 | 365 | 366 | /*28. Find the Index of the First Occurrence in a String (Easy) 367 | Given two strings needle and haystack, return the index of the first occurrence 368 | of needle in haystack, or -1 if needle is not part of haystack. 369 | 370 | Example 1: 371 | Input: haystack = "sadbutsad", needle = "sad" 372 | Output: 0 373 | Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, 374 | so we return 0. 375 | 376 | Example 2: 377 | Input: haystack = "leetcode", needle = "leeto" 378 | Output: -1 379 | Explanation: "leeto" did not occur in "leetcode", so we return -1. 380 | 381 | Constraints: 382 | * 1 <= haystack.length, needle.length <= 10^4 383 | * haystack and needle consist of only lowercase English characters.*/ 384 | 385 | func strStr(haystack string, needle string) int { 386 | return strings.Index(haystack, needle) 387 | } 388 | 389 | 390 | /*35. Search Insert Position (Easy) 391 | Given a sorted array of distinct integers and a target value, return the index 392 | if the target is found. If not, return the index where it would be if it were 393 | inserted in order. You must write an algorithm with O(log n) runtime complexity. 394 | 395 | Example 1: 396 | Input: nums = [1,3,5,6], target = 5 397 | Output: 2 398 | 399 | Example 2: 400 | Input: nums = [1,3,5,6], target = 2 401 | Output: 1 402 | 403 | Example 3: 404 | Input: nums = [1,3,5,6], target = 7 405 | Output: 4 406 | 407 | Constraints: 408 | * 1 <= nums.length <= 10^4 409 | * -10^4 <= nums[i] <= 10^4 410 | * nums contains distinct values sorted in ascending order. 411 | * -10^4 <= target <= 10^4*/ 412 | 413 | func searchInsert(nums []int, target int) int { 414 | k, _ := slices.BinarySearch(nums, target) 415 | return k 416 | } 417 | 418 | 419 | /*58. Length of Last Word (Easy) 420 | Given a string s consisting of words and spaces, return the length of the last 421 | word in the string. A word is a maximal substring consisting of non-space 422 | characters only. 423 | 424 | Example 1: 425 | Input: s = "Hello World" 426 | Output: 5 427 | Explanation: The last word is "World" with length 5. 428 | 429 | Example 2: 430 | Input: s = " fly me to the moon " 431 | Output: 4 432 | Explanation: The last word is "moon" with length 4. 433 | 434 | Example 3: 435 | Input: s = "luffy is still joyboy" 436 | Output: 6 437 | Explanation: The last word is "joyboy" with length 6. 438 | 439 | Constraints: 440 | * 1 <= s.length <= 10^4 441 | * s consists of only English letters and spaces ' '. 442 | * There will be at least one word in s.*/ 443 | 444 | func lengthOfLastWord(s string) int { 445 | words := strings.Fields(s) 446 | return len(words[len(words)-1]) 447 | } 448 | 449 | 450 | /*66. Plus One (Easy) 451 | You are given a large integer represented as an integer array digits, where each 452 | digits[i] is the ith digit of the integer. The digits are ordered from most 453 | significant to least significant in left-to-right order. The large integer does 454 | not contain any leading 0's. Increment the large integer by one and return the 455 | resulting array of digits. 456 | 457 | Example 1: 458 | Input: digits = [1,2,3] 459 | Output: [1,2,4] 460 | Explanation: The array represents the integer 123. Incrementing by one gives 461 | 123 + 1 = 124. Thus, the result should be [1,2,4]. 462 | 463 | Example 2: 464 | Input: digits = [4,3,2,1] 465 | Output: [4,3,2,2] 466 | Explanation: The array represents the integer 4321. Incrementing by one gives 467 | 4321 + 1 = 4322. Thus, the result should be [4,3,2,2]. 468 | 469 | Example 3: 470 | Input: digits = [9] 471 | Output: [1,0] 472 | Explanation: The array represents the integer 9. Incrementing by one gives 473 | 9 + 1 = 10. Thus, the result should be [1,0]. 474 | 475 | Constraints: 476 | * 1 <= digits.length <= 100 477 | * 0 <= digits[i] <= 9 478 | * digits does not contain any leading 0's.*/ 479 | 480 | func plusOne(digits []int) []int { 481 | carry := 1 482 | for i := len(digits)-1; i >= 0 && carry == 1; i-- { 483 | carry += digits[i] 484 | digits[i] = carry % 10 485 | carry /= 10 486 | } 487 | if (carry == 1) { 488 | digits = append([]int{1}, digits...) 489 | } 490 | return digits 491 | } 492 | 493 | 494 | /*70. Climbing Stairs (Easy) 495 | You are climbing a staircase. It takes n steps to reach the top. Each time you 496 | can either climb 1 or 2 steps. In how many distinct ways can you climb to the 497 | top? 498 | 499 | Example 1: 500 | Input: n = 2 501 | Output: 2 502 | Explanation: There are two ways to climb to the top. 503 | 1. 1 step + 1 step 504 | 2. 2 steps 505 | 506 | Example 2: 507 | Input: n = 3 508 | Output: 3 509 | Explanation: There are three ways to climb to the top. 510 | 1. 1 step + 1 step + 1 step 511 | 2. 1 step + 2 steps 512 | 3. 2 steps + 1 step 513 | 514 | Constraints: 1 <= n <= 45*/ 515 | 516 | func climbStairs(n int) int { 517 | f0, f1 := 0, 1 518 | for ; n > 0; n-- { 519 | f0, f1 = f1, f0+f1 520 | } 521 | return f1 522 | } 523 | 524 | 525 | /*83. Remove Duplicates from Sorted List (Easy) 526 | Given the head of a sorted linked list, delete all duplicates such that each 527 | element appears only once. Return the linked list sorted as well. 528 | 529 | Example 1: 530 | Input: head = [1,1,2] 531 | Output: [1,2] 532 | 533 | Example 2: 534 | Input: head = [1,1,2,3,3] 535 | Output: [1,2,3] 536 | 537 | Constraints: 538 | * The number of nodes in the list is in the range [0, 300]. 539 | * -100 <= Node.val <= 100 540 | * The list is guaranteed to be sorted in ascending order.*/ 541 | 542 | func deleteDuplicates(head *ListNode) *ListNode { 543 | node := head 544 | for node != nil && node.Next != nil { 545 | if node.Val == node.Next.Val { 546 | node.Next = node.Next.Next 547 | } else { 548 | node = node.Next 549 | } 550 | } 551 | return head 552 | } 553 | 554 | 555 | /*88. Merge Sorted Array (Easy) 556 | You are given two integer arrays nums1 and nums2, sorted in non-decreasing 557 | order, and two integers m and n, representing the number of elements in nums1 558 | and nums2 respectively. Merge nums1 and nums2 into a single array sorted in non- 559 | decreasing order. The final sorted array should not be returned by the function, 560 | but instead be stored inside the array nums1. To accommodate this, nums1 has a 561 | length of m + n, where the first m elements denote the elements that should be 562 | merged, and the last n elements are set to 0 and should be ignored. nums2 has a 563 | length of n. 564 | 565 | Example 1: 566 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 567 | Output: [1,2,2,3,5,6] 568 | Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of 569 | the merge is [1,2,2,3,5,6] with the underlined elements coming from 570 | nums1. 571 | 572 | Example 2: 573 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 574 | Output: [1] 575 | Explanation: The arrays we are merging are [1] and []. The result of the merge 576 | is [1]. 577 | 578 | Example 3: 579 | Input: nums1 = [0], m = 0, nums2 = [1], n = 1 580 | Output: [1] 581 | Explanation: The arrays we are merging are [] and [1]. The result of the merge 582 | is [1]. Note that because m = 0, there are no elements in nums1. 583 | The 0 is only there to ensure the merge result can fit in nums1. 584 | 585 | Constraints: 586 | * nums1.length == m + n 587 | * nums2.length == n 588 | * 0 <= m, n <= 200 589 | * 1 <= m + n <= 200 590 | * -10^9 <= nums1[i], nums2[j] <= 10^9 591 | 592 | Follow up: Can you come up with an algorithm that runs in O(m + n) time?*/ 593 | 594 | func merge(nums1 []int, m int, nums2 []int, n int) { 595 | for i, j := m-1, n-1; j >= 0; { 596 | if i >= 0 && nums1[i] > nums2[j] { 597 | nums1[i+j+1] = nums1[i] 598 | i-- 599 | } else { 600 | nums1[i+j+1] = nums2[j] 601 | j-- 602 | } 603 | } 604 | } 605 | 606 | 607 | /*94. Binary Tree Inorder Traversal (Easy) 608 | Given the root of a binary tree, return the inorder traversal of its nodes' 609 | values. 610 | 611 | Example 1: 612 | Input: root = [1,null,2,3] 613 | Output: [1,3,2] 614 | Explanation: 615 | 616 | Example 2: 617 | Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] 618 | Output: [4,2,6,5,7,1,3,9,8] 619 | Explanation: 620 | 621 | Example 3: 622 | Input: root = [] 623 | Output: [] 624 | 625 | Example 4: 626 | Input: root = [1] 627 | Output: [1] 628 | 629 | Constraints: 630 | * The number of nodes in the tree is in the range [0, 100]. 631 | * -100 <= Node.val <= 100 632 | 633 | Follow up: Recursive solution is trivial, could you do it iteratively?*/ 634 | 635 | func inorderTraversal(root *TreeNode) []int { 636 | ans := []int{} 637 | stack := []*TreeNode{} 638 | node := root 639 | for node != nil || len(stack) > 0 { 640 | if node != nil { 641 | stack = append(stack, node) 642 | node = node.Left 643 | } else { 644 | sz := len(stack) 645 | node = stack[sz-1] 646 | stack = stack[:sz-1] 647 | ans = append(ans, node.Val) 648 | node = node.Right 649 | } 650 | } 651 | return ans 652 | } 653 | 654 | 655 | /*100. Same Tree (Easy) 656 | Given the roots of two binary trees p and q, write a function to check if they 657 | are the same or not. Two binary trees are considered the same if they are 658 | structurally identical, and the nodes have the same value. 659 | 660 | Example 1: 661 | Input: p = [1,2,3], q = [1,2,3] 662 | Output: true 663 | 664 | Example 2: 665 | Input: p = [1,2], q = [1,null,2] 666 | Output: false 667 | 668 | Example 3: 669 | Input: p = [1,2,1], q = [1,1,2] 670 | Output: false 671 | 672 | Constraints: 673 | * The number of nodes in both trees is in the range [0, 100]. 674 | * -10^4 <= Node.val <= 10^4*/ 675 | 676 | func isSameTree(p *TreeNode, q *TreeNode) bool { 677 | if p == nil && q == nil { 678 | return true 679 | } else if (p == nil || q == nil) { 680 | return false 681 | } else { 682 | return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right) 683 | } 684 | } 685 | 686 | 687 | /*101. Symmetric Tree (Easy) 688 | Given the root of a binary tree, check whether it is a mirror of itself (i.e., 689 | symmetric around its center). 690 | 691 | Example 1: 692 | Input: root = [1,2,2,3,4,4,3] 693 | Output: true 694 | 695 | Example 2: 696 | Input: root = [1,2,2,null,3,null,3] 697 | Output: false 698 | 699 | Constraints: 700 | * The number of nodes in the tree is in the range [1, 1000]. 701 | * -100 <= Node.val <= 100 702 | 703 | Follow up: Could you solve it both recursively and iteratively?*/ 704 | 705 | func isSymmetric(root *TreeNode) bool { 706 | var check func(left, right *TreeNode) bool 707 | 708 | check = func(left, right *TreeNode) bool { 709 | if left == nil || right == nil { 710 | return left == right 711 | } else { 712 | return left.Val == right.Val && check(left.Left, right.Right) && check(left.Right, right.Left) 713 | } 714 | } 715 | 716 | return check(root.Left, root.Right) 717 | } 718 | 719 | 720 | /*104. Maximum Depth of Binary Tree (Easy) 721 | Given the root of a binary tree, return its maximum depth. A binary tree's 722 | maximum depth is the number of nodes along the longest path from the root node 723 | down to the farthest leaf node. 724 | 725 | Example 1: 726 | Input: root = [3,9,20,null,null,15,7] 727 | Output: 3 728 | 729 | Example 2: 730 | Input: root = [1,null,2] 731 | Output: 2 732 | 733 | Constraints: 734 | * The number of nodes in the tree is in the range [0, 10^4]. 735 | * -100 <= Node.val <= 100*/ 736 | 737 | func maxDepth(root *TreeNode) int { 738 | if root == nil { 739 | return 0 740 | } 741 | return 1 + max(maxDepth(root.Left), maxDepth(root.Right)) 742 | } 743 | 744 | 745 | /*108. Convert Sorted Array to Binary Search Tree (Easy) 746 | Given an integer array nums where the elements are sorted in ascending order, 747 | convert it to a height-balanced binary search tree. 748 | 749 | Example 1: 750 | Input: nums = [-10,-3,0,5,9] 751 | Output: [0,-3,9,-10,null,5] 752 | Explanation: [0,-10,5,null,-3,null,9] is also accepted: 753 | 754 | Example 2: 755 | Input: nums = [1,3] 756 | Output: [3,1] 757 | Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. 758 | 759 | Constraints: 760 | * 1 <= nums.length <= 10^4 761 | * -10^4 <= nums[i] <= 10^4 762 | * nums is sorted in a strictly increasing order.*/ 763 | 764 | func sortedArrayToBST(nums []int) *TreeNode { 765 | if len(nums) == 0 { 766 | return nil 767 | } 768 | mid := len(nums)/2 769 | return &TreeNode{nums[mid], sortedArrayToBST(nums[:mid]), sortedArrayToBST(nums[mid+1:])} 770 | } 771 | 772 | 773 | /*110. Balanced Binary Tree (Easy) 774 | Given a binary tree, determine if it is height-balanced. 775 | 776 | Example 1: 777 | Input: root = [3,9,20,null,null,15,7] 778 | Output: true 779 | 780 | Example 2: 781 | Input: root = [1,2,2,3,3,null,null,4,4] 782 | Output: false 783 | 784 | Example 3: 785 | Input: root = [] 786 | Output: true 787 | 788 | Constraints: 789 | * The number of nodes in the tree is in the range [0, 5000]. 790 | * -10^4 <= Node.val <= 10^4*/ 791 | 792 | func isBalanced(root *TreeNode) bool { 793 | var calc func(node *TreeNode) int 794 | 795 | calc = func(node *TreeNode) int { 796 | if node == nil { 797 | return 0 798 | } 799 | left := calc(node.Left) 800 | right := calc(node.Right) 801 | if left == -1 || right == -1 || math.Abs(float64(left-right)) > 1 { 802 | return -1 803 | } 804 | return 1 + max(left, right) 805 | } 806 | 807 | return calc(root) != -1 808 | } 809 | 810 | 811 | /*111. Minimum Depth of Binary Tree (Easy) 812 | Given a binary tree, find its minimum depth. The minimum depth is the number of 813 | nodes along the shortest path from the root node down to the nearest leaf node. 814 | Note: A leaf is a node with no children. 815 | 816 | Example 1: 817 | Input: root = [3,9,20,null,null,15,7] 818 | Output: 2 819 | 820 | Example 2: 821 | Input: root = [2,null,3,null,4,null,5,null,6] 822 | Output: 5 823 | 824 | Constraints: 825 | * The number of nodes in the tree is in the range [0, 10^5]. 826 | * -1000 <= Node.val <= 1000*/ 827 | 828 | func minDepth(root *TreeNode) int { 829 | if root == nil { 830 | return 0 831 | } 832 | left, right := minDepth(root.Left), minDepth(root.Right) 833 | if left == 0 || right == 0 { 834 | return 1 + left + right 835 | } else { 836 | return 1 + min(left, right) 837 | } 838 | } 839 | 840 | 841 | /*112. Path Sum (Easy) 842 | Given the root of a binary tree and an integer targetSum, return true if the 843 | tree has a root-to-leaf path such that adding up all the values along the path 844 | equals targetSum. A leaf is a node with no children. 845 | 846 | Example 1: 847 | Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 848 | Output: true 849 | Explanation: The root-to-leaf path with the target sum is shown. 850 | 851 | Example 2: 852 | Input: root = [1,2,3], targetSum = 5 853 | Output: false 854 | Explanation: There are two root-to-leaf paths in the tree: 855 | (1 --> 2): The sum is 3. 856 | (1 --> 3): The sum is 4. 857 | There is no root-to-leaf path with sum = 5. 858 | 859 | Example 3: 860 | Input: root = [], targetSum = 0 861 | Output: false 862 | Explanation: Since the tree is empty, there are no root-to-leaf paths. 863 | 864 | Constraints: 865 | * The number of nodes in the tree is in the range [0, 5000]. 866 | * -1000 <= Node.val <= 1000 867 | * -1000 <= targetSum <= 1000*/ 868 | 869 | func hasPathSum(root *TreeNode, targetSum int) bool { 870 | if root == nil { 871 | return false 872 | } 873 | if root.Left == nil && root.Right == nil { 874 | return targetSum == root.Val 875 | } 876 | return hasPathSum(root.Left, targetSum-root.Val) || hasPathSum(root.Right, targetSum-root.Val) 877 | } 878 | 879 | 880 | /*118. Pascal's Triangle (Easy) 881 | Given an integer numRows, return the first numRows of Pascal's triangle. In 882 | Pascal's triangle, each number is the sum of the two numbers directly above it 883 | as shown: 884 | 885 | Example 1: 886 | Input: numRows = 5 887 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] 888 | 889 | Example 2: 890 | Input: numRows = 1 891 | Output: [[1]] 892 | 893 | Constraints: 1 <= numRows <= 30*/ 894 | 895 | func generate(numRows int) [][]int { 896 | ans := make([][]int, numRows) 897 | for i := 0; i < numRows; i++ { 898 | ans[i] = make([]int, i+1) 899 | ans[i][0] = 1 900 | ans[i][i] = 1 901 | for j := 1; j < i; j++ { 902 | ans[i][j] = ans[i-1][j-1] + ans[i-1][j] 903 | } 904 | } 905 | return ans 906 | } 907 | 908 | 909 | /*119. Pascal's Triangle II (Easy) 910 | Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's 911 | triangle. In Pascal's triangle, each number is the sum of the two numbers 912 | directly above it as shown: 913 | 914 | Example 1: 915 | Input: rowIndex = 3 916 | Output: [1,3,3,1] 917 | 918 | Example 2: 919 | Input: rowIndex = 0 920 | Output: [1] 921 | 922 | Example 3: 923 | Input: rowIndex = 1 924 | Output: [1,1] 925 | 926 | Constraints: 0 <= rowIndex <= 33 927 | 928 | Follow up: Could you optimize your algorithm to use only O(rowIndex) extra space?*/ 929 | 930 | func getRow(rowIndex int) []int { 931 | ans := make([]int, rowIndex+1) 932 | ans[0] = 1 933 | for i := 1; i <= rowIndex; i++ { 934 | ans[i] = ans[i-1] * (rowIndex-i+1) / i 935 | } 936 | return ans 937 | } 938 | 939 | 940 | /*121. Best Time to Buy and Sell Stock (Easy) 941 | You are given an array prices where prices[i] is the price of a given stock on 942 | the ith day. You want to maximize your profit by choosing a single day to buy 943 | one stock and choosing a different day in the future to sell that stock. Return 944 | the maximum profit you can achieve from this transaction. If you cannot achieve 945 | any profit, return 0. 946 | 947 | Example 1: 948 | Input: prices = [7,1,5,3,6,4] 949 | Output: 5 950 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), 951 | profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is 952 | not allowed because you must buy before you sell. 953 | 954 | Example 2: 955 | Input: prices = [7,6,4,3,1] 956 | Output: 0 957 | Explanation: In this case, no transactions are done and the max profit = 0. 958 | 959 | Constraints: 960 | * 1 <= prices.length <= 10^5 961 | * 0 <= prices[i] <= 10^4*/ 962 | 963 | func maxProfit(prices []int) int { 964 | ans := 0 965 | val := 0 966 | for i := 1; i < len(prices); i++ { 967 | val = max(0, val + prices[i] - prices[i-1]) 968 | ans = max(ans, val) 969 | } 970 | return ans 971 | } 972 | 973 | 974 | /*125. Valid Palindrome (Easy) 975 | A phrase is a palindrome if, after converting all uppercase letters into 976 | lowercase letters and removing all non-alphanumeric characters, it reads the 977 | same forward and backward. Alphanumeric characters include letters and numbers. 978 | Given a string s, return true if it is a palindrome, or false otherwise. 979 | 980 | Example 1: 981 | Input: s = "A man, a plan, a canal: Panama" 982 | Output: true 983 | Explanation: "amanaplanacanalpanama" is a palindrome. 984 | 985 | Example 2: 986 | Input: s = "race a car" 987 | Output: false 988 | Explanation: "raceacar" is not a palindrome. 989 | 990 | Example 3: 991 | Input: s = " " 992 | Output: true 993 | Explanation: s is an empty string "" after removing non-alphanumeric characters. 994 | Since an empty string reads the same forward and backward, it is a 995 | palindrome. 996 | 997 | Constraints: 998 | * 1 <= s.length <= 2 * 10^5 999 | * s consists only of printable ASCII characters.*/ 1000 | 1001 | func isPalindrome(s string) bool { 1002 | s = strings.Map(func(ch rune) rune { 1003 | if unicode.IsLetter(ch) || unicode.IsNumber(ch) { 1004 | return unicode.ToLower(ch) 1005 | } 1006 | return -1 1007 | }, s) 1008 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 1009 | if (s[i] != s[j]) { 1010 | return false 1011 | } 1012 | } 1013 | return true 1014 | } 1015 | 1016 | 1017 | /*136. Single Number (Easy) 1018 | Given a non-empty array of integers nums, every element appears twice except for 1019 | one. Find that single one. You must implement a solution with a linear runtime 1020 | complexity and use only constant extra space. 1021 | 1022 | Example 1: 1023 | Input: nums = [2,2,1] 1024 | Output: 1 1025 | 1026 | Example 2: 1027 | Input: nums = [4,1,2,1,2] 1028 | Output: 4 1029 | 1030 | Example 3: 1031 | Input: nums = [1] 1032 | Output: 1 1033 | 1034 | Constraints: 1035 | * 1 <= nums.length <= 3 * 10^4 1036 | * -3 * 10^4 <= nums[i] <= 3 * 10^4 1037 | * Each element in the array appears twice except for one element which appears 1038 | only once.*/ 1039 | 1040 | func singleNumber(nums []int) int { 1041 | ans := 0 1042 | for _, x := range nums { 1043 | ans ^= x 1044 | } 1045 | return ans 1046 | } 1047 | 1048 | 1049 | /*141. Linked List Cycle (Easy) 1050 | Given head, the head of a linked list, determine if the linked list has a cycle 1051 | in it. There is a cycle in a linked list if there is some node in the list that 1052 | can be reached again by continuously following the next pointer. Internally, pos 1053 | is used to denote the index of the node that tail's next pointer is connected 1054 | to. Note that pos is not passed as a parameter. Return true if there is a cycle 1055 | in the linked list. Otherwise, return false. 1056 | 1057 | Example 1: 1058 | Input: head = [3,2,0,-4], pos = 1 1059 | Output: true 1060 | Explanation: There is a cycle in the linked list, where the tail connects to the 1061 | 1st node (0-indexed). 1062 | 1063 | Example 2: 1064 | Input: head = [1,2], pos = 0 1065 | Output: true 1066 | Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. 1067 | 1068 | Example 3: 1069 | Input: head = [1], pos = -1 1070 | Output: false 1071 | Explanation: There is no cycle in the linked list. 1072 | 1073 | Constraints: 1074 | * The number of the nodes in the list is in the range [0, 10^4]. 1075 | * -10^5 <= Node.val <= 10^5 1076 | * pos is -1 or a valid index in the linked-list. 1077 | 1078 | Follow up: Can you solve it using O(1) (i.e. constant) memory?*/ 1079 | 1080 | func hasCycle(head *ListNode) bool { 1081 | fast := head 1082 | slow := head 1083 | for fast != nil && fast.Next != nil { 1084 | fast = fast.Next.Next 1085 | slow = slow.Next 1086 | if fast == slow { 1087 | return true 1088 | } 1089 | } 1090 | return false 1091 | } 1092 | 1093 | 1094 | /*144. Binary Tree Preorder Traversal (Easy) 1095 | Given the root of a binary tree, return the preorder traversal of its nodes' 1096 | values. 1097 | 1098 | Example 1: 1099 | Input: root = [1,null,2,3] 1100 | Output: [1,2,3] 1101 | Explanation: 1102 | 1103 | Example 2: 1104 | Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] 1105 | Output: [1,2,4,5,6,7,3,8,9] 1106 | Explanation: 1107 | 1108 | Example 3: 1109 | Input: root = [] 1110 | Output: [] 1111 | 1112 | Example 4: 1113 | Input: root = [1] 1114 | Output: [1] 1115 | 1116 | Constraints: 1117 | * The number of nodes in the tree is in the range [0, 100]. 1118 | * -100 <= Node.val <= 100 1119 | 1120 | Follow up: Recursive solution is trivial, could you do it iteratively?*/ 1121 | 1122 | func preorderTraversal(root *TreeNode) []int { 1123 | ans := []int{} 1124 | if root != nil { 1125 | stack := []*TreeNode{root} 1126 | for len(stack) > 0 { 1127 | sz := len(stack) 1128 | node := stack[sz-1] 1129 | stack = stack[:sz-1] 1130 | ans = append(ans, node.Val) 1131 | if node.Right != nil { stack = append(stack, node.Right) } 1132 | if node.Left != nil {stack = append(stack, node.Left) } 1133 | } 1134 | } 1135 | return ans 1136 | } 1137 | 1138 | 1139 | /*145. Binary Tree Postorder Traversal (Easy) 1140 | Given the root of a binary tree, return the postorder traversal of its nodes' 1141 | values. 1142 | 1143 | Example 1: 1144 | Input: root = [1,null,2,3] 1145 | Output: [3,2,1] 1146 | Explanation: 1147 | 1148 | Example 2: 1149 | Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] 1150 | Output: [4,6,7,5,2,9,8,3,1] 1151 | Explanation: 1152 | 1153 | Example 3: 1154 | Input: root = [] 1155 | Output: [] 1156 | 1157 | Example 4: 1158 | Input: root = [1] 1159 | Output: [1] 1160 | 1161 | Constraints: 1162 | * The number of the nodes in the tree is in the range [0, 100]. 1163 | * -100 <= Node.val <= 100 1164 | 1165 | Follow up: Recursive solution is trivial, could you do it iteratively?*/ 1166 | 1167 | func postorderTraversal(root *TreeNode) []int { 1168 | ans := []int{} 1169 | 1170 | var dfs func(node *TreeNode) 1171 | dfs = func(node *TreeNode) { 1172 | if node != nil { 1173 | dfs(node.Left) 1174 | dfs(node.Right) 1175 | ans = append(ans, node.Val) 1176 | } 1177 | } 1178 | 1179 | dfs(root) 1180 | return ans 1181 | } 1182 | 1183 | 1184 | /*160. Intersection of Two Linked Lists (Easy) 1185 | Given the heads of two singly linked-lists headA and headB, return the node at 1186 | which the two lists intersect. If the two linked lists have no intersection at 1187 | all, return null. For example, the following two linked lists begin to intersect 1188 | at node c1: 1189 | The test cases are generated such that there are no cycles anywhere in the 1190 | entire linked structure. Note that the linked lists must retain their original 1191 | structure after the function returns. 1192 | 1193 | Custom Judge: 1194 | The inputs to the judge are given as follows (your program is not given these 1195 | inputs): 1196 | * intersectVal - The value of the node where the intersection occurs. This is 0 1197 | if there is no intersected node. 1198 | * listA - The first linked list. 1199 | * listB - The second linked list. 1200 | * skipA - The number of nodes to skip ahead in listA (starting from the head) to 1201 | get to the intersected node. 1202 | * skipB - The number of nodes to skip ahead in listB (starting from the head) to 1203 | get to the intersected node. 1204 | The judge will then create the linked structure based on these inputs and pass 1205 | the two heads, headA and headB to your program. If you correctly return the 1206 | intersected node, then your solution will be accepted. 1207 | 1208 | Example 1: 1209 | Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 1210 | Output: Intersected at '8' 1211 | Explanation: The intersected node's value is 8 (note that this must not be 0 if 1212 | the two lists intersect). From the head of A, it reads as 1213 | [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There 1214 | are 2 nodes before the intersected node in A; There are 3 nodes 1215 | before the intersected node in B. 1216 | - Note that the intersected node's value is not 1 because the nodes 1217 | with value 1 in A and B (2nd node in A and 3rd node in B) are 1218 | different node references. In other words, they point to two 1219 | different locations in memory, while the nodes with value 8 in A 1220 | and B (3rd node in A and 4th node in B) point to the same 1221 | location in memory. 1222 | 1223 | Example 2: 1224 | Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 1225 | Output: Intersected at '2' 1226 | Explanation: The intersected node's value is 2 (note that this must not be 0 if 1227 | the two lists intersect). From the head of A, it reads as 1228 | [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 1229 | nodes before the intersected node in A; There are 1 node before the 1230 | intersected node in B. 1231 | 1232 | Example 3: 1233 | Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 1234 | Output: No intersection 1235 | Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it 1236 | reads as [1,5]. Since the two lists do not intersect, intersectVal 1237 | must be 0, while skipA and skipB can be arbitrary values. 1238 | Explanation: The two lists do not intersect, so return null. 1239 | 1240 | Constraints: 1241 | * The number of nodes of listA is in the m. 1242 | * The number of nodes of listB is in the n. 1243 | * 1 <= m, n <= 3 * 104 1244 | * 1 <= Node.val <= 105 1245 | * 0 <= skipA <= m 1246 | * 0 <= skipB <= n 1247 | * intersectVal is 0 if listA and listB do not intersect. 1248 | * intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect. 1249 | 1250 | Follow up: Could you write a solution that runs in O(m + n) time and use only 1251 | O(1) memory?*/ 1252 | 1253 | func getIntersectionNode(headA, headB *ListNode) *ListNode { 1254 | nodeA, nodeB := headA, headB 1255 | for nodeA != nodeB { 1256 | if nodeA == nil { 1257 | nodeA = headB 1258 | } else { 1259 | nodeA = nodeA.Next 1260 | } 1261 | if nodeB == nil { 1262 | nodeB = headA 1263 | } else { 1264 | nodeB = nodeB.Next 1265 | } 1266 | } 1267 | return nodeA 1268 | } 1269 | 1270 | 1271 | /*168. Excel Sheet Column Title (Easy) 1272 | Given an integer columnNumber, return its corresponding column title as it 1273 | appears in an Excel sheet. For example: 1274 | A -> 1 1275 | B -> 2 1276 | C -> 3 1277 | ... 1278 | Z -> 26 1279 | AA -> 27 1280 | AB -> 28 1281 | ... 1282 | 1283 | Example 1: 1284 | Input: columnNumber = 1 1285 | Output: "A" 1286 | 1287 | Example 2: 1288 | Input: columnNumber = 28 1289 | Output: "AB" 1290 | 1291 | Example 3: 1292 | Input: columnNumber = 701 1293 | Output: "ZY" 1294 | 1295 | Constraints: 1 <= columnNumber <= 2^31 - 1*/ 1296 | 1297 | func convertToTitle(columnNumber int) string { 1298 | ans := []byte{} 1299 | for columnNumber > 0 { 1300 | columnNumber-- 1301 | ans = append(ans, byte(columnNumber%26 + 'A')) 1302 | columnNumber /= 26 1303 | } 1304 | for i, j := 0, len(ans)-1; i < j; i, j = i+1, j-1 { 1305 | ans[i], ans[j] = ans[j], ans[i] 1306 | } 1307 | return string(ans) 1308 | } 1309 | 1310 | 1311 | /*169. Majority Element (Easy) 1312 | Given an array nums of size n, return the majority element. The majority element 1313 | is the element that appears more than ⌊n / 2⌋ times. You may assume that the 1314 | majority element always exists in the array. 1315 | 1316 | Example 1: 1317 | Input: nums = [3,2,3] 1318 | Output: 3 1319 | 1320 | Example 2: 1321 | Input: nums = [2,2,1,1,1,2,2] 1322 | Output: 2 1323 | 1324 | Constraints: 1325 | * n == nums.length 1326 | * 1 <= n <= 5 * 10^4 1327 | * -10^9 <= nums[i] <= 10^9 1328 | 1329 | Follow-up: Could you solve the problem in linear time and in O(1) space?*/ 1330 | 1331 | func majorityElement(nums []int) int { 1332 | cand := 0 1333 | vote := 0 1334 | for _, x := range nums { 1335 | if vote == 0 || cand == x{ 1336 | vote++ 1337 | cand = x 1338 | } else { 1339 | vote-- 1340 | } 1341 | } 1342 | return cand 1343 | } 1344 | 1345 | 1346 | /*171. Excel Sheet Column Number (Easy) 1347 | Given a string columnTitle that represents the column title as appears in an 1348 | Excel sheet, return its corresponding column number. For example: 1349 | A -> 1 1350 | B -> 2 1351 | C -> 3 1352 | ... 1353 | Z -> 26 1354 | AA -> 27 1355 | AB -> 28 1356 | ... 1357 | 1358 | Example 1: 1359 | Input: columnTitle = "A" 1360 | Output: 1 1361 | 1362 | Example 2: 1363 | Input: columnTitle = "AB" 1364 | Output: 28 1365 | 1366 | Example 3: 1367 | Input: columnTitle = "ZY" 1368 | Output: 701 1369 | 1370 | Constraints: 1371 | * 1 <= columnTitle.length <= 7 1372 | * columnTitle consists only of uppercase English letters. 1373 | * columnTitle is in the range ["A", "FXSHRXW"].*/ 1374 | 1375 | func titleToNumber(columnTitle string) int { 1376 | ans := 0 1377 | for _, ch := range columnTitle { 1378 | ans = 26*ans + int(ch-'A') + 1 1379 | } 1380 | return ans 1381 | } 1382 | 1383 | 1384 | /*190. Reverse Bits (Easy) 1385 | Reverse bits of a given 32 bits unsigned integer. 1386 | 1387 | Note: 1388 | * Note that in some languages, such as Java, there is no unsigned integer type. 1389 | In this case, both input and output will be given as a signed integer type. 1390 | They should not affect your implementation, as the integer's internal binary 1391 | representation is the same, whether it is signed or unsigned. 1392 | * In Java, the compiler represents the signed integers using 2's complement 1393 | notation. Therefore, in Example 2 above, the input represents the signed 1394 | integer -3 and the output represents the signed integer -1073741825. 1395 | 1396 | Example 1: 1397 | Input: n = 00000010100101000001111010011100 1398 | Output: 964176192 (00111001011110000010100101000000) 1399 | Explanation: The input binary string 00000010100101000001111010011100 represents 1400 | the unsigned integer 43261596, so return 964176192 which its binary 1401 | representation is 00111001011110000010100101000000. 1402 | Example 2: 1403 | Input: n = 11111111111111111111111111111101 1404 | Output: 3221225471 (10111111111111111111111111111111) 1405 | Explanation: The input binary string 11111111111111111111111111111101 represents 1406 | the unsigned integer 4294967293, so return 3221225471 which its 1407 | binary representation is 10111111111111111111111111111111. 1408 | 1409 | Constraints: The input must be a binary string of length 32 1410 | 1411 | Follow up: If this function is called many times, how would you optimize it?*/ 1412 | 1413 | func reverseBits(num uint32) uint32 { 1414 | var ans uint32 1415 | for i := 0; i < 32; i++ { 1416 | ans = ans<<1 + num & 1 1417 | num >>= 1 1418 | } 1419 | return ans 1420 | } 1421 | 1422 | 1423 | /*191. Number of 1 Bits (Easy) 1424 | Given a positive integer n, write a function that returns the number of set bits 1425 | in its binary representation (also known as the Hamming weight). 1426 | 1427 | Example 1: 1428 | Input: n = 11 1429 | Output: 3 1430 | Explanation: The input binary string 1011 has a total of three set bits. 1431 | 1432 | Example 2: 1433 | Input: n = 128 1434 | Output: 1 1435 | Explanation: The input binary string 10000000 has a total of one set bit. 1436 | 1437 | Example 3: 1438 | Input: n = 2147483645 1439 | Output: 30 1440 | Explanation: The input binary string 1111111111111111111111111111101 has a total 1441 | of thirty set bits. 1442 | 1443 | Constraints: 1 <= n <= 2^31 - 1 1444 | 1445 | Follow up: If this function is called many times, how would you optimize it?*/ 1446 | 1447 | func hammingWeight(n int) int { 1448 | return bits.OnesCount(uint(n)) 1449 | } 1450 | 1451 | 1452 | /*202. Happy Number (Easy) 1453 | Write an algorithm to determine if a number n is happy. A happy number is a 1454 | number defined by the following process: 1455 | * Starting with any positive integer, replace the number by the sum of the 1456 | squares of its digits. 1457 | * Repeat the process until the number equals 1 (where it will stay), or it loops 1458 | endlessly in a cycle which does not include 1. 1459 | * Those numbers for which this process ends in 1 are happy. 1460 | Return true if n is a happy number, and false if not. 1461 | 1462 | Example 1: 1463 | Input: n = 19 1464 | Output: true 1465 | Explanation: 12 + 92 = 82 1466 | 82 + 22 = 68 1467 | 62 + 82 = 100 1468 | 12 + 02 + 02 = 1 1469 | Example 2: 1470 | Input: n = 2 1471 | Output: false 1472 | 1473 | Constraints: 1 <= n <= 2^31 - 1*/ 1474 | 1475 | func isHappy(n int) bool { 1476 | calc := func(n int) int { 1477 | ans := 0 1478 | for ; n > 0; n /= 10 { 1479 | ans += (n % 10) * (n % 10) 1480 | } 1481 | return ans 1482 | } 1483 | for f, s := n, n; f != 1 && calc(f) != 1; { 1484 | f = calc(calc(f)) 1485 | s = calc(s) 1486 | if f == s { 1487 | return false 1488 | } 1489 | } 1490 | return true 1491 | } 1492 | 1493 | 1494 | /*203. Remove Linked List Elements (Easy) 1495 | Given the head of a linked list and an integer val, remove all the nodes of the 1496 | linked list that has Node.val == val, and return the new head. 1497 | 1498 | Example 1: 1499 | Input: head = [1,2,6,3,4,5,6], val = 6 1500 | Output: [1,2,3,4,5] 1501 | 1502 | Example 2: 1503 | Input: head = [], val = 1 1504 | Output: [] 1505 | 1506 | Example 3: 1507 | Input: head = [7,7,7,7], val = 7 1508 | Output: [] 1509 | 1510 | Constraints: 1511 | * The number of nodes in the list is in the range [0, 10^4]. 1512 | * 1 <= Node.val <= 50 1513 | * 0 <= val <= 50*/ 1514 | 1515 | func removeElements(head *ListNode, val int) *ListNode { 1516 | dummy := &ListNode{0, head} 1517 | for node := dummy; node.Next != nil; { 1518 | if node.Next.Val == val { 1519 | node.Next = node.Next.Next 1520 | } else { 1521 | node = node.Next 1522 | } 1523 | } 1524 | return dummy.Next 1525 | } 1526 | 1527 | 1528 | /*205. Isomorphic Strings (Easy) 1529 | Given two strings s and t, determine if they are isomorphic. Two strings s and t 1530 | are isomorphic if the characters in s can be replaced to get t. All occurrences 1531 | of a character must be replaced with another character while preserving the 1532 | order of characters. No two characters may map to the same character, but a 1533 | character may map to itself. 1534 | 1535 | Example 1: 1536 | Input: s = "egg", t = "add" 1537 | Output: true 1538 | Explanation: The strings s and t can be made identical by: 1539 | Mapping 'e' to 'a'. 1540 | Mapping 'g' to 'd'. 1541 | 1542 | Example 2: 1543 | Input: s = "foo", t = "bar" 1544 | Output: false 1545 | Explanation: The strings s and t can not be made identical as 'o' needs to be 1546 | mapped to both 'a' and 'r'. 1547 | 1548 | Example 3: 1549 | Input: s = "paper", t = "title" 1550 | Output: true 1551 | 1552 | Constraints: 1553 | * 1 <= s.length <= 5 * 10^4 1554 | * t.length == s.length 1555 | * s and t consist of any valid ascii character.*/ 1556 | 1557 | func isIsomorphic(s string, t string) bool { 1558 | si := map[byte]int{} 1559 | ti := map[byte]int{} 1560 | for i := range s { 1561 | if si[s[i]] != ti[t[i]] { 1562 | return false 1563 | } 1564 | si[s[i]] = i+1 1565 | ti[t[i]] = i+1 1566 | } 1567 | return true 1568 | } 1569 | 1570 | 1571 | /*206. Reverse Linked List (Easy) 1572 | Given the head of a singly linked list, reverse the list, and return the 1573 | reversed list. 1574 | 1575 | Example 1: 1576 | Input: head = [1,2,3,4,5] 1577 | Output: [5,4,3,2,1] 1578 | 1579 | Example 2: 1580 | Input: head = [1,2] 1581 | Output: [2,1] 1582 | 1583 | Example 3: 1584 | Input: head = [] 1585 | Output: [] 1586 | 1587 | Constraints: 1588 | * The number of nodes in the list is the range [0, 5000]. 1589 | * -5000 <= Node.val <= 5000 1590 | 1591 | Follow up: A linked list can be reversed either iteratively or recursively. 1592 | Could you implement both?*/ 1593 | 1594 | func reverseList(head *ListNode) *ListNode { 1595 | var prev *ListNode 1596 | for curr := head; curr != nil; { 1597 | next := curr.Next 1598 | curr.Next = prev 1599 | prev, curr = curr, next 1600 | } 1601 | return prev 1602 | } 1603 | 1604 | 1605 | /*217. Contains Duplicate (Easy) 1606 | Given an integer array nums, return true if any value appears at least twice in 1607 | the array, and return false if every element is distinct. 1608 | 1609 | Example 1: 1610 | Input: nums = [1,2,3,1] 1611 | Output: true 1612 | Explanation: The element 1 occurs at the indices 0 and 3. 1613 | 1614 | Example 2: 1615 | Input: nums = [1,2,3,4] 1616 | Output: false 1617 | Explanation: All elements are distinct. 1618 | 1619 | Example 3: 1620 | Input: nums = [1,1,1,3,3,4,3,2,4,2] 1621 | Output: true 1622 | 1623 | Constraints: 1624 | * 1 <= nums.length <= 10^5 1625 | * -10^9 <= nums[i] <= 10^9*/ 1626 | 1627 | func containsDuplicate(nums []int) bool { 1628 | seen := map[int]struct{}{} 1629 | for _, x := range nums { 1630 | if _, ok := seen[x]; ok { 1631 | return true 1632 | } 1633 | seen[x] = struct{}{} 1634 | } 1635 | return false 1636 | } 1637 | 1638 | 1639 | /*219. Contains Duplicate II (Easy) 1640 | Given an integer array nums and an integer k, return true if there are two 1641 | distinct indices i and j in the array such that nums[i] == nums[j] and 1642 | abs(i - j) <= k. 1643 | 1644 | Example 1: 1645 | Input: nums = [1,2,3,1], k = 3 1646 | Output: true 1647 | 1648 | Example 2: 1649 | Input: nums = [1,0,1,1], k = 1 1650 | Output: true 1651 | 1652 | Example 3: 1653 | Input: nums = [1,2,3,1,2,3], k = 2 1654 | Output: false 1655 | 1656 | Constraints: 1657 | * 1 <= nums.length <= 10^5 1658 | * -10^9 <= nums[i] <= 10^9 1659 | * 0 <= k <= 10^5*/ 1660 | 1661 | func containsNearbyDuplicate(nums []int, k int) bool { 1662 | seen := map[int]int{} 1663 | for i, x := range nums { 1664 | if j, ok := seen[x]; ok && i-j <= k { 1665 | return true 1666 | } 1667 | seen[x] = i 1668 | } 1669 | return false 1670 | } 1671 | 1672 | 1673 | /*222. Count Complete Tree Nodes (Easy) 1674 | Given the root of a complete binary tree, return the number of the nodes in the 1675 | tree. According to Wikipedia, every level, except possibly the last, is 1676 | completely filled in a complete binary tree, and all nodes in the last level are 1677 | as far left as possible. It can have between 1 and 2h nodes inclusive at the 1678 | last level h. Design an algorithm that runs in less than O(n) time complexity. 1679 | 1680 | Example 1: 1681 | Input: root = [1,2,3,4,5,6] 1682 | Output: 6 1683 | 1684 | Example 2: 1685 | Input: root = [] 1686 | Output: 0 1687 | 1688 | Example 3: 1689 | Input: root = [1] 1690 | Output: 1 1691 | 1692 | Constraints: 1693 | * The number of nodes in the tree is in the range [0, 5 * 10^4]. 1694 | * 0 <= Node.val <= 5 * 10^4 1695 | * The tree is guaranteed to be complete.*/ 1696 | 1697 | func countNodes(root *TreeNode) int { 1698 | ht := func(node *TreeNode) int { 1699 | ans := 0 1700 | for ; node != nil; node = node.Left { 1701 | ans++ 1702 | } 1703 | return ans 1704 | } 1705 | 1706 | var fn func(node *TreeNode) int 1707 | fn = func(node *TreeNode) int { 1708 | if node == nil { 1709 | return 0 1710 | } 1711 | h := ht(node.Left) 1712 | if h == ht(node.Right) { 1713 | return 1<b" if a != b 1826 | * "a" if a == b 1827 | 1828 | Example 1: 1829 | Input: nums = [0,1,2,4,5,7] 1830 | Output: ["0->2","4->5","7"] 1831 | Explanation: The ranges are: 1832 | [0,2] --> "0->2" 1833 | [4,5] --> "4->5" 1834 | [7,7] --> "7" 1835 | 1836 | Example 2: 1837 | Input: nums = [0,2,3,4,6,8,9] 1838 | Output: ["0","2->4","6","8->9"] 1839 | Explanation: The ranges are: 1840 | [0,0] --> "0" 1841 | [2,4] --> "2->4" 1842 | [6,6] --> "6" 1843 | [8,9] --> "8->9" 1844 | 1845 | Constraints: 1846 | * 0 <= nums.length <= 20 1847 | * -2^31 <= nums[i] <= 2^31 - 1 1848 | * All the values of nums are unique. 1849 | * nums is sorted in ascending order.*/ 1850 | 1851 | func summaryRanges(nums []int) []string { 1852 | ans := []string{} 1853 | lo := 0 1854 | for i, x := range nums { 1855 | if i == 0 || nums[i-1]+1 < x { 1856 | lo = x 1857 | } 1858 | if i+1 == len(nums) || x+1 < nums[i+1] { 1859 | if lo == x { 1860 | ans = append(ans, strconv.Itoa(lo)) 1861 | } else { 1862 | ans = append(ans, fmt.Sprintf("%d->%d", lo, x)) 1863 | } 1864 | } 1865 | } 1866 | return ans 1867 | } 1868 | 1869 | 1870 | /*231. Power of Two (Easy) 1871 | Given an integer n, return true if it is a power of two. Otherwise, return 1872 | false. An integer n is a power of two, if there exists an integer x such that 1873 | n == 2^x. 1874 | 1875 | Example 1: 1876 | Input: n = 1 1877 | Output: true 1878 | Explanation: 20 = 1 1879 | 1880 | Example 2: 1881 | Input: n = 16 1882 | Output: true 1883 | Explanation: 24 = 16 1884 | 1885 | Example 3: 1886 | Input: n = 3 1887 | Output: false 1888 | 1889 | Constraints: -2^31 <= n <= 2^31 - 1 1890 | 1891 | Follow up: Could you solve it without loops/recursion?*/ 1892 | 1893 | func isPowerOfTwo(n int) bool { 1894 | return n > 0 && n&(n-1) == 0 1895 | } 1896 | 1897 | 1898 | /*232. Implement Queue using Stacks (Easy) 1899 | Implement a first in first out (FIFO) queue using only two stacks. The 1900 | implemented queue should support all the functions of a normal queue (push, 1901 | peek, pop, and empty). Implement the MyQueue class: 1902 | * void push(int x) Pushes element x to the back of the queue. 1903 | * int pop() Removes the element from the front of the queue and returns it. 1904 | * int peek() Returns the element at the front of the queue. 1905 | * boolean empty() Returns true if the queue is empty, false otherwise. 1906 | 1907 | Notes: 1908 | * You must use only standard operations of a stack, which means only push to 1909 | top, peek/pop from top, size, and is empty operations are valid. 1910 | * Depending on your language, the stack may not be supported natively. You may 1911 | simulate a stack using a list or deque (double-ended queue) as long as you use 1912 | only a stack's standard operations. 1913 | 1914 | Example 1: 1915 | Input: ["MyQueue", "push", "push", "peek", "pop", "empty"] 1916 | [[], [1], [2], [], [], []] 1917 | Output: [null, null, null, 1, 1, false] 1918 | Explanation 1919 | MyQueue myQueue = new MyQueue(); 1920 | myQueue.push(1); // queue is: [1] 1921 | myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue) 1922 | myQueue.peek(); // return 1 1923 | myQueue.pop(); // return 1, queue is [2] 1924 | myQueue.empty(); // return false 1925 | 1926 | Constraints: 1927 | * 1 <= x <= 9 1928 | * At most 100 calls will be made to push, pop, peek, and empty. 1929 | * All the calls to pop and peek are valid. 1930 | 1931 | Follow-up: Can you implement the queue such that each operation is amortized 1932 | O(1) time complexity? In other words, performing n operations will 1933 | take overall O(n) time even if one of those operations may take 1934 | longer.*/ 1935 | 1936 | type MyQueue struct { 1937 | sin []int 1938 | sout []int 1939 | } 1940 | 1941 | 1942 | func Constructor() MyQueue { 1943 | return MyQueue{ 1944 | sin: []int{}, 1945 | sout: []int{}, 1946 | } 1947 | } 1948 | 1949 | 1950 | func (this *MyQueue) Push(x int) { 1951 | this.sin = append(this.sin, x) 1952 | } 1953 | 1954 | 1955 | func (this *MyQueue) Move() { 1956 | for sz := len(this.sin); sz > 0; sz-- { 1957 | this.sout = append(this.sout, this.sin[sz-1]) 1958 | this.sin = this.sin[:sz-1] 1959 | } 1960 | } 1961 | 1962 | func (this *MyQueue) Pop() int { 1963 | if len(this.sout) == 0 { 1964 | this.Move() 1965 | } 1966 | sz := len(this.sout) 1967 | elem := this.sout[sz-1] 1968 | this.sout = this.sout[:sz-1] 1969 | return elem 1970 | } 1971 | 1972 | 1973 | func (this *MyQueue) Peek() int { 1974 | if len(this.sout) == 0 { 1975 | this.Move() 1976 | } 1977 | sz := len(this.sout) 1978 | return this.sout[sz-1] 1979 | } 1980 | 1981 | 1982 | func (this *MyQueue) Empty() bool { 1983 | return len(this.sin) == 0 && len(this.sout) == 0 1984 | } 1985 | 1986 | 1987 | /*234. Palindrome Linked List (Easy) 1988 | Given the head of a singly linked list, return true if it is a palindrome or 1989 | false otherwise. 1990 | 1991 | Example 1: 1992 | Input: head = [1,2,2,1] 1993 | Output: true 1994 | 1995 | Example 2: 1996 | Input: head = [1,2] 1997 | Output: false 1998 | 1999 | Constraints: 2000 | * The number of nodes in the list is in the range [1, 10^5]. 2001 | * 0 <= Node.val <= 9 2002 | 2003 | Follow up: Could you do it in O(n) time and O(1) space?*/ 2004 | 2005 | func isPalindrome(head *ListNode) bool { 2006 | fast := head 2007 | slow := head 2008 | for fast != nil && fast.Next != nil { 2009 | fast = fast.Next.Next 2010 | slow = slow.Next 2011 | } 2012 | var prev *ListNode = nil 2013 | for slow != nil { 2014 | prev, slow.Next, slow = slow, prev, slow.Next 2015 | } 2016 | for head != nil && prev != nil { 2017 | if head.Val != prev.Val { 2018 | return false 2019 | } 2020 | head = head.Next 2021 | prev = prev.Next 2022 | } 2023 | return true 2024 | } 2025 | 2026 | 2027 | /*242. Valid Anagram (Easy) 2028 | Given two strings s and t, return true if t is an anagram of s, and false 2029 | otherwise. 2030 | 2031 | Example 1: 2032 | Input: s = "anagram", t = "nagaram" 2033 | Output: true 2034 | 2035 | Example 2: 2036 | Input: s = "rat", t = "car" 2037 | Output: false 2038 | 2039 | Constraints: 2040 | * 1 <= s.length, t.length <= 5 * 10^4 2041 | * s and t consist of lowercase English letters. 2042 | 2043 | Follow up: What if the inputs contain Unicode characters? How would you adapt 2044 | your solution to such a case?*/ 2045 | 2046 | func isAnagram(s string, t string) bool { 2047 | freq := map[rune]int{} 2048 | for _, ch := range s { 2049 | freq[ch]++ 2050 | } 2051 | for _, ch := range t { 2052 | freq[ch]-- 2053 | } 2054 | for _, v := range freq { 2055 | if v != 0 { 2056 | return false 2057 | } 2058 | } 2059 | return true 2060 | } 2061 | 2062 | 2063 | /*257. Binary Tree Paths (Easy) 2064 | Given the root of a binary tree, return all root-to-leaf paths in any order. A 2065 | leaf is a node with no children. 2066 | 2067 | Example 1: 2068 | Input: root = [1,2,3,null,5] 2069 | Output: ["1->2->5","1->3"] 2070 | 2071 | Example 2: 2072 | Input: root = [1] 2073 | Output: ["1"] 2074 | 2075 | Constraints: 2076 | * The number of nodes in the tree is in the range [1, 100]. 2077 | * -100 <= Node.val <= 100*/ 2078 | 2079 | func binaryTreePaths(root *TreeNode) []string { 2080 | ans := []string{} 2081 | vals := []int{} 2082 | 2083 | var dfs func(node *TreeNode) 2084 | dfs = func(node *TreeNode) { 2085 | vals = append(vals, node.Val) 2086 | if node.Left == nil && node.Right == nil { 2087 | elem := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(vals)), "->"), "[]") 2088 | ans = append(ans, elem) 2089 | } else { 2090 | if node.Left != nil { 2091 | dfs(node.Left) 2092 | } 2093 | if node.Right != nil { 2094 | dfs(node.Right) 2095 | } 2096 | } 2097 | vals = vals[:len(vals)-1] 2098 | } 2099 | 2100 | dfs(root) 2101 | return ans 2102 | } 2103 | 2104 | 2105 | /*258. Add Digits (Easy) 2106 | Given an integer num, repeatedly add all its digits until the result has only 2107 | one digit, and return it. 2108 | 2109 | Example 1: 2110 | Input: num = 38 2111 | Output: 2 2112 | Explanation: The process is 2113 | 38 --> 3 + 8 --> 11 2114 | 11 --> 1 + 1 --> 2 2115 | Since 2 has only one digit, return it. 2116 | 2117 | Example 2: 2118 | Input: num = 0 2119 | Output: 0 2120 | 2121 | Constraints: 0 <= num <= 2^31 - 1 2122 | 2123 | Follow up: Could you do it without any loop/recursion in O(1) runtime?*/ 2124 | 2125 | func addDigits(num int) int { 2126 | return (num-1) % 9 + 1 2127 | } 2128 | 2129 | 2130 | /*263. Ugly Number (Easy) 2131 | An ugly number is a positive integer which does not have a prime factor other 2132 | than 2, 3, and 5. Given an integer n, return true if n is an ugly number. 2133 | 2134 | Example 1: 2135 | Input: n = 6 2136 | Output: true 2137 | Explanation: 6 = 2 × 3 2138 | 2139 | Example 2: 2140 | Input: n = 1 2141 | Output: true 2142 | Explanation: 1 has no prime factors. 2143 | 2144 | Example 3: 2145 | Input: n = 14 2146 | Output: false 2147 | Explanation: 14 is not ugly since it includes the prime factor 7. 2148 | 2149 | Constraints: -2^31 <= n <= 2^31 - 1*/ 2150 | 2151 | func isUgly(n int) bool { 2152 | if n <= 0 { 2153 | return false 2154 | } 2155 | for _, p := range []int{2, 3, 5} { 2156 | for n % p == 0 { 2157 | n /= p 2158 | } 2159 | } 2160 | return n == 1 2161 | } 2162 | 2163 | 2164 | /*268. Missing Number (Easy) 2165 | Given an array nums containing n distinct numbers in the range [0, n], return 2166 | the only number in the range that is missing from the array. 2167 | 2168 | Example 1: 2169 | Input: nums = [3,0,1] 2170 | Output: 2 2171 | Explanation: n = 3 since there are 3 numbers, so all numbers are in the range 2172 | [0,3]. 2 is the missing number in the range since it does not 2173 | appear in nums. 2174 | 2175 | Example 2: 2176 | Input: nums = [0,1] 2177 | Output: 2 2178 | Explanation: n = 2 since there are 2 numbers, so all numbers are in the range 2179 | [0,2]. 2 is the missing number in the range since it does not 2180 | appear in nums. 2181 | 2182 | Example 3: 2183 | Input: nums = [9,6,4,2,3,5,7,0,1] 2184 | Output: 8 2185 | Explanation: n = 9 since there are 9 numbers, so all numbers are in the range 2186 | [0,9]. 8 is the missing number in the range since it does not 2187 | appear in nums. 2188 | 2189 | Constraints: 2190 | * n == nums.length 2191 | * 1 <= n <= 10^4 2192 | * 0 <= nums[i] <= n 2193 | * All the numbers of nums are unique. 2194 | 2195 | Follow up: Could you implement a solution using only O(1) extra space complexity 2196 | and O(n) runtime complexity?*/ 2197 | 2198 | func missingNumber(nums []int) int { 2199 | m := 0 2200 | for i, x := range nums { 2201 | m ^= x 2202 | m ^= i+1 2203 | } 2204 | return m 2205 | } 2206 | 2207 | 2208 | /*278. First Bad Version (Easy) 2209 | You are a product manager and currently leading a team to develop a new product. 2210 | Unfortunately, the latest version of your product fails the quality check. Since 2211 | each version is developed based on the previous version, all the versions after 2212 | a bad version are also bad. Suppose you have n versions [1, 2, ..., n] and you 2213 | want to find out the first bad one, which causes all the following ones to be 2214 | bad. You are given an API bool isBadVersion(version) which returns whether 2215 | version is bad. Implement a function to find the first bad version. You should 2216 | minimize the number of calls to the API. 2217 | 2218 | Example 1: 2219 | Input: n = 5, bad = 4 2220 | Output: 4 2221 | Explanation: - call isBadVersion(3) -> false 2222 | - call isBadVersion(5) -> true 2223 | - call isBadVersion(4) -> true 2224 | Then 4 is the first bad version. 2225 | 2226 | Example 2: 2227 | Input: n = 1, bad = 1 2228 | Output: 1 2229 | 2230 | Constraints: 1 <= bad <= n <= 2^31 - 1*/ 2231 | 2232 | func firstBadVersion(n int) int { 2233 | lo, hi := 1, n 2234 | for lo < hi { 2235 | mid := (lo + hi)/2 2236 | if isBadVersion(mid) { 2237 | hi = mid 2238 | } else { 2239 | lo = mid+1 2240 | } 2241 | } 2242 | return lo 2243 | } 2244 | 2245 | 2246 | /*283. Move Zeroes (Easy) 2247 | Given an integer array nums, move all 0's to the end of it while maintaining the 2248 | relative order of the non-zero elements. Note that you must do this in-place 2249 | without making a copy of the array. 2250 | 2251 | Example 1: 2252 | Input: nums = [0,1,0,3,12] 2253 | Output: [1,3,12,0,0] 2254 | 2255 | Example 2: 2256 | Input: nums = [0] 2257 | Output: [0] 2258 | 2259 | Constraints: 2260 | * 1 <= nums.length <= 10^4 2261 | * -2^31 <= nums[i] <= 2^31 - 1 2262 | 2263 | Follow up: Could you minimize the total number of operations done?*/ 2264 | 2265 | func moveZeroes(nums []int) { 2266 | k := 0 2267 | for i, x := range nums { 2268 | if x != 0 { 2269 | nums[k], nums[i] = nums[i], nums[k] 2270 | k++ 2271 | } 2272 | } 2273 | } 2274 | 2275 | 2276 | /*290. Word Pattern (Easy) 2277 | Given a pattern and a string s, find if s follows the same pattern. Here follow 2278 | means a full match, such that there is a bijection between a letter in pattern 2279 | and a non-empty word in s. Specifically: 2280 | * Each letter in pattern maps to exactly one unique word in s. 2281 | * Each unique word in s maps to exactly one letter in pattern. 2282 | * No two letters map to the same word, and no two words map to the same letter. 2283 | 2284 | Example 1: 2285 | Input: pattern = "abba", s = "dog cat cat dog" 2286 | Output: true 2287 | Explanation: The bijection can be established as: 2288 | - 'a' maps to "dog". 2289 | - 'b' maps to "cat". 2290 | 2291 | Example 2: 2292 | Input: pattern = "abba", s = "dog cat cat fish" 2293 | Output: false 2294 | 2295 | Example 3: 2296 | Input: pattern = "aaaa", s = "dog cat cat dog" 2297 | Output: false 2298 | 2299 | Constraints: 2300 | * 1 <= pattern.length <= 300 2301 | * pattern contains only lower-case English letters. 2302 | * 1 <= s.length <= 3000 2303 | * s contains only lowercase English letters and spaces ' '. 2304 | * s does not contain any leading or trailing spaces. 2305 | * All the words in s are separated by a single space.*/ 2306 | 2307 | func wordPattern(pattern string, s string) bool { 2308 | words := strings.Split(s, " ") 2309 | if len(pattern) != len(words) { 2310 | return false 2311 | } 2312 | pi := map[rune]int{} 2313 | wi := map[string]int{} 2314 | for i, ch := range pattern { 2315 | if pi[ch] != wi[words[i]] { 2316 | return false 2317 | } 2318 | pi[ch] = i+1 2319 | wi[words[i]] = i+1 2320 | } 2321 | return true 2322 | } 2323 | 2324 | 2325 | /*292. Nim Game (Easy) 2326 | You are playing the following Nim Game with your friend: 2327 | * Initially, there is a heap of stones on the table. 2328 | * You and your friend will alternate taking turns, and you go first. 2329 | * On each turn, the person whose turn it is will remove 1 to 3 stones from the 2330 | heap. 2331 | * The one who removes the last stone is the winner. 2332 | Given n, the number of stones in the heap, return true if you can win the game 2333 | assuming both you and your friend play optimally, otherwise return false. 2334 | 2335 | Example 1: 2336 | Input: n = 4 2337 | Output: false 2338 | Explanation: These are the possible outcomes: 2339 | 1. You remove 1 stone. Your friend removes 3 stones, including the 2340 | last stone. Your friend wins. 2341 | 2. You remove 2 stones. Your friend removes 2 stones, including the 2342 | last stone. Your friend wins. 2343 | 3. You remove 3 stones. Your friend removes the last stone. Your 2344 | friend wins. 2345 | In all outcomes, your friend wins. 2346 | 2347 | Example 2: 2348 | Input: n = 1 2349 | Output: true 2350 | 2351 | Example 3: 2352 | Input: n = 2 2353 | Output: true 2354 | 2355 | Constraints: 1 <= n <= 2^31 - 1*/ 2356 | 2357 | func canWinNim(n int) bool { 2358 | return n % 4 != 0 2359 | } 2360 | 2361 | 2362 | /*303. Range Sum Query - Immutable (Easy) 2363 | Given an integer array nums, handle multiple queries of the following type: 2364 | * Calculate the sum of the elements of nums between indices left and right 2365 | inclusive where left <= right. 2366 | Implement the NumArray class: 2367 | * NumArray(int[] nums) Initializes the object with the integer array nums. 2368 | * int sumRange(int left, int right) Returns the sum of the elements of nums 2369 | between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + 2370 | ... + nums[right]). 2371 | 2372 | Example 1: 2373 | Input: ["NumArray", "sumRange", "sumRange", "sumRange"] 2374 | [[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]] 2375 | Output: [null, 1, -1, -3] 2376 | Explanation: - NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]); 2377 | - numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1 2378 | - numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1 2379 | - numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) 2380 | = -3 2381 | 2382 | Constraints: 2383 | * 1 <= nums.length <= 10^4 2384 | * -10^5 <= nums[i] <= 10^5 2385 | * 0 <= left <= right < nums.length 2386 | * At most 10^4 calls will be made to sumRange.*/ 2387 | 2388 | type NumArray struct { 2389 | prefix []int 2390 | } 2391 | 2392 | 2393 | func Constructor(nums []int) NumArray { 2394 | n := len(nums) 2395 | prefix := make([]int, n+1) 2396 | for i := 0; i < n; i++ { 2397 | prefix[i+1] = prefix[i] + nums[i] 2398 | } 2399 | return NumArray{ 2400 | prefix : prefix, 2401 | } 2402 | } 2403 | 2404 | 2405 | func (this *NumArray) SumRange(left int, right int) int { 2406 | return this.prefix[right+1] - this.prefix[left] 2407 | } 2408 | 2409 | 2410 | /*326. Power of Three (Easy) 2411 | Given an integer n, return true if it is a power of three. Otherwise, return 2412 | false. An integer n is a power of three, if there exists an integer x such that 2413 | n == 3x. 2414 | 2415 | Example 1: 2416 | Input: n = 27 2417 | Output: true 2418 | Explanation: 27 = 33 2419 | 2420 | Example 2: 2421 | Input: n = 0 2422 | Output: false 2423 | Explanation: There is no x where 3x = 0. 2424 | 2425 | Example 3: 2426 | Input: n = -1 2427 | Output: false 2428 | Explanation: There is no x where 3x = (-1). 2429 | 2430 | Constraints: -2^31 <= n <= 2^31 - 1 2431 | 2432 | Follow up: Could you solve it without loops/recursion?*/ 2433 | 2434 | func isPowerOfThree(n int) bool { 2435 | return n > 0 && 1162261467 % n == 0 2436 | } 2437 | 2438 | 2439 | /*338. Counting Bits (Easy) 2440 | Given an integer n, return an array ans of length n + 1 such that for each i 2441 | (0 <= i <= n), ans[i] is the number of 1's in the binary representation of i. 2442 | 2443 | Example 1: 2444 | Input: n = 2 2445 | Output: [0,1,1] 2446 | Explanation: 0 --> 0 2447 | 1 --> 1 2448 | 2 --> 10 2449 | 2450 | Example 2: 2451 | Input: n = 5 2452 | Output: [0,1,1,2,1,2] 2453 | Explanation: 0 --> 0 2454 | 1 --> 1 2455 | 2 --> 10 2456 | 3 --> 11 2457 | 4 --> 100 2458 | 5 --> 101 2459 | 2460 | Constraints: 0 <= n <= 10^5 2461 | 2462 | Follow up: 2463 | * It is very easy to come up with a solution with a runtime of O(n log n). Can 2464 | you do it in linear time O(n) and possibly in a single pass? 2465 | * Can you do it without using any built-in function (i.e., like 2466 | __builtin_popcount in C++)?*/ 2467 | 2468 | func countBits(n int) []int { 2469 | ans := make([]int, n+1) 2470 | for x := 0; x <= n; x++ { 2471 | ans[x] = ans[x >> 1] + x&1 2472 | } 2473 | return ans 2474 | } 2475 | 2476 | 2477 | /*342. Power of Four (Easy) 2478 | Given an integer n, return true if it is a power of four. Otherwise, return 2479 | false. An integer n is a power of four, if there exists an integer x such that 2480 | n == 4x. 2481 | 2482 | Example 1: 2483 | Input: n = 16 2484 | Output: true 2485 | 2486 | Example 2: 2487 | Input: n = 5 2488 | Output: false 2489 | 2490 | Example 3: 2491 | Input: n = 1 2492 | Output: true 2493 | 2494 | Constraints: -2^31 <= n <= 2^31 - 1 2495 | 2496 | Follow up: Could you solve it without loops/recursion?*/ 2497 | 2498 | func isPowerOfFour(n int) bool { 2499 | return n > 0 && n&(n-1) == 0 && (n-1) % 3 == 0 2500 | } 2501 | 2502 | 2503 | /*344. Reverse String (Easy) 2504 | Write a function that reverses a string. The input string is given as an array 2505 | of characters s. You must do this by modifying the input array in-place with 2506 | O(1) extra memory. 2507 | 2508 | Example 1: 2509 | Input: s = ["h","e","l","l","o"] 2510 | Output: ["o","l","l","e","h"] 2511 | 2512 | Example 2: 2513 | Input: s = ["H","a","n","n","a","h"] 2514 | Output: ["h","a","n","n","a","H"] 2515 | 2516 | Constraints: 2517 | * 1 <= s.length <= 10^5 2518 | * s[i] is a printable ascii character.*/ 2519 | 2520 | func reverseString(s []byte) { 2521 | for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { 2522 | s[i], s[j] = s[j], s[i] 2523 | } 2524 | } 2525 | 2526 | 2527 | /*345. Reverse Vowels of a String (Easy) 2528 | Given a string s, reverse only all the vowels in the string and return it. The 2529 | vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and 2530 | upper cases, more than once. 2531 | 2532 | Example 1: 2533 | Input: s = "IceCreAm" 2534 | Output: "AceCreIm" 2535 | Explanation: The vowels in s are ['I', 'e', 'e', 'A']. On reversing the vowels, 2536 | s becomes "AceCreIm". 2537 | 2538 | Example 2: 2539 | Input: s = "leetcode" 2540 | Output: "leotcede" 2541 | 2542 | Constraints: 2543 | * 1 <= s.length <= 3 * 10^5 2544 | * s consist of printable ASCII characters.*/ 2545 | 2546 | func reverseVowels(s string) string { 2547 | runes := []rune(s) 2548 | vowel := "aeiouAEIOU" 2549 | for i, j := 0, len(runes)-1; i < j; { 2550 | if !strings.ContainsRune(vowel, runes[i]) { 2551 | i++ 2552 | } else if !strings.ContainsRune(vowel, runes[j]) { 2553 | j-- 2554 | } else { 2555 | runes[i], runes[j] = runes[j], runes[i] 2556 | i++ 2557 | j-- 2558 | } 2559 | } 2560 | return string(runes) 2561 | } 2562 | 2563 | 2564 | /*349. Intersection of Two Arrays (Easy) 2565 | Given two integer arrays nums1 and nums2, return an array of their intersection. 2566 | Each element in the result must be unique and you may return the result in any 2567 | order. 2568 | 2569 | Example 1: 2570 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 2571 | Output: [2] 2572 | 2573 | Example 2: 2574 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 2575 | Output: [9,4] 2576 | Explanation: [4,9] is also accepted. 2577 | 2578 | Constraints: 2579 | * 1 <= nums1.length, nums2.length <= 1000 2580 | * 0 <= nums1[i], nums2[i] <= 1000*/ 2581 | 2582 | func intersection(nums1 []int, nums2 []int) []int { 2583 | seen := map[int]bool{} 2584 | for _, x := range nums1 { 2585 | seen[x] = true 2586 | } 2587 | ans := []int{} 2588 | for _, x := range nums2 { 2589 | if seen[x] { 2590 | ans = append(ans, x) 2591 | seen[x] = false 2592 | } 2593 | } 2594 | return ans 2595 | } 2596 | 2597 | 2598 | /*350. Intersection of Two Arrays II (Easy) 2599 | Given two integer arrays nums1 and nums2, return an array of their intersection. 2600 | Each element in the result must appear as many times as it shows in both arrays 2601 | and you may return the result in any order. 2602 | 2603 | Example 1: 2604 | Input: nums1 = [1,2,2,1], nums2 = [2,2] 2605 | Output: [2,2] 2606 | 2607 | Example 2: 2608 | Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 2609 | Output: [4,9] 2610 | Explanation: [9,4] is also accepted. 2611 | 2612 | Constraints: 2613 | * 1 <= nums1.length, nums2.length <= 1000 2614 | * 0 <= nums1[i], nums2[i] <= 1000 2615 | 2616 | Follow up: 2617 | * What if the given array is already sorted? How would you optimize your 2618 | algorithm? 2619 | * What if nums1's size is small compared to nums2's size? Which algorithm is 2620 | better? 2621 | * What if elements of nums2 are stored on disk, and the memory is limited such 2622 | that you cannot load all elements into the memory at once?*/ 2623 | 2624 | func intersect(nums1 []int, nums2 []int) []int { 2625 | freq := map[int]int{} 2626 | for _, x := range nums1 { 2627 | freq[x]++ 2628 | } 2629 | ans := []int{} 2630 | for _, x := range nums2 { 2631 | if freq[x] > 0 { 2632 | ans = append(ans, x) 2633 | freq[x]-- 2634 | } 2635 | } 2636 | return ans 2637 | } 2638 | 2639 | 2640 | /*367. Valid Perfect Square (Easy) 2641 | Given a positive integer num, return true if num is a perfect square or false 2642 | otherwise. A perfect square is an integer that is the square of an integer. In 2643 | other words, it is the product of some integer with itself. You must not use any 2644 | built-in library function, such as sqrt. 2645 | 2646 | Example 1: 2647 | Input: num = 16 2648 | Output: true 2649 | Explanation: We return true because 4 * 4 = 16 and 4 is an integer. 2650 | 2651 | Example 2: 2652 | Input: num = 14 2653 | Output: false 2654 | Explanation: We return false because 3.742 * 3.742 = 14 and 3.742 is not an 2655 | integer. 2656 | 2657 | Constraints: 1 <= num <= 2^31 - 1*/ 2658 | 2659 | func isPerfectSquare(num int) bool { 2660 | x := max(1, num-1) 2661 | for x > num/x { 2662 | x = (x + num/x)/2 2663 | } 2664 | return x * x == num 2665 | } 2666 | 2667 | 2668 | /*374. Guess Number Higher or Lower (Easy) 2669 | We are playing the Guess Game. The game is as follows: I pick a number from 1 to 2670 | n. You have to guess which number I picked. Every time you guess wrong, I will 2671 | tell you whether the number I picked is higher or lower than your guess. You 2672 | call a pre-defined API int guess(int num), which returns three possible results: 2673 | * -1: Your guess is higher than the number I picked (i.e. num > pick). 2674 | * 1: Your guess is lower than the number I picked (i.e. num < pick). 2675 | * 0: your guess is equal to the number I picked (i.e. num == pick). 2676 | Return the number that I picked. 2677 | 2678 | Example 1: 2679 | Input: n = 10, pick = 6 2680 | Output: 6 2681 | 2682 | Example 2: 2683 | Input: n = 1, pick = 1 2684 | Output: 1 2685 | 2686 | Example 3: 2687 | Input: n = 2, pick = 1 2688 | Output: 1 2689 | 2690 | Constraints: 2691 | * 1 <= n <= 2^31 - 1 2692 | * 1 <= pick <= n*/ 2693 | 2694 | func guessNumber(n int) int { 2695 | lo, hi := 1, n 2696 | for lo <= hi { 2697 | mid := (lo+hi) / 2 2698 | switch guess(mid) { 2699 | case -1: hi = mid-1 2700 | case 1: lo = mid+1 2701 | default: return mid 2702 | } 2703 | } 2704 | return lo 2705 | } 2706 | 2707 | 2708 | /*383. Ransom Note (Easy) 2709 | Given two strings ransomNote and magazine, return true if ransomNote can be 2710 | constructed by using the letters from magazine and false otherwise. Each letter 2711 | in magazine can only be used once in ransomNote. 2712 | 2713 | Example 1: 2714 | Input: ransomNote = "a", magazine = "b" 2715 | Output: false 2716 | 2717 | Example 2: 2718 | Input: ransomNote = "aa", magazine = "ab" 2719 | Output: false 2720 | 2721 | Example 3: 2722 | Input: ransomNote = "aa", magazine = "aab" 2723 | Output: true 2724 | 2725 | Constraints: 2726 | * 1 <= ransomNote.length, magazine.length <= 10^5 2727 | * ransomNote and magazine consist of lowercase English letters.*/ 2728 | 2729 | func canConstruct(ransomNote string, magazine string) bool { 2730 | freq := make([]int, 26) 2731 | for _, ch := range magazine { 2732 | freq[ch - 'a']++ 2733 | } 2734 | for _, ch := range ransomNote { 2735 | freq[ch - 'a']-- 2736 | if freq[ch - 'a'] < 0 { 2737 | return false 2738 | } 2739 | } 2740 | return true 2741 | } 2742 | 2743 | 2744 | /*387. First Unique Character in a String (Easy) 2745 | Given a string s, find the first non-repeating character in it and return its 2746 | index. If it does not exist, return -1. 2747 | 2748 | Example 1: 2749 | Input: s = "leetcode" 2750 | Output: 0 2751 | Explanation: The character 'l' at index 0 is the first character that does not 2752 | occur at any other index. 2753 | 2754 | Example 2: 2755 | Input: s = "loveleetcode" 2756 | Output: 2 2757 | 2758 | Example 3: 2759 | Input: s = "aabb" 2760 | Output: -1 2761 | 2762 | Constraints: 2763 | * 1 <= s.length <= 10^5 2764 | * s consists of only lowercase English letters.*/ 2765 | 2766 | func firstUniqChar(s string) int { 2767 | freq := make([]int, 26) 2768 | for _, ch := range s { 2769 | freq[ch - 'a']++ 2770 | } 2771 | for i, ch := range s { 2772 | if freq[ch - 'a'] == 1 { 2773 | return i 2774 | } 2775 | } 2776 | return -1 2777 | } 2778 | 2779 | 2780 | /*389. Find the Difference (Easy) 2781 | You are given two strings s and t. String t is generated by random shuffling 2782 | string s and then add one more letter at a random position. Return the letter 2783 | that was added to t. 2784 | 2785 | Example 1: 2786 | Input: s = "abcd", t = "abcde" 2787 | Output: "e" 2788 | Explanation: 'e' is the letter that was added. 2789 | 2790 | Example 2: 2791 | Input: s = "", t = "y" 2792 | Output: "y" 2793 | 2794 | Constraints: 2795 | * 0 <= s.length <= 1000 2796 | * t.length == s.length + 1 2797 | * s and t consist of lowercase English letters.*/ 2798 | 2799 | func findTheDifference(s string, t string) byte { 2800 | ans := byte(0) 2801 | for _, ch := range s { 2802 | ans -= byte(ch) 2803 | } 2804 | for _, ch := range t { 2805 | ans += byte(ch) 2806 | } 2807 | return ans 2808 | } 2809 | 2810 | 2811 | /*392. Is Subsequence (Easy) 2812 | Given two strings s and t, return true if s is a subsequence of t, or false 2813 | otherwise. A subsequence of a string is a new string that is formed from the 2814 | original string by deleting some (can be none) of the characters without 2815 | disturbing the relative positions of the remaining characters. (i.e., "ace" is a 2816 | subsequence of "abcde" while "aec" is not). 2817 | 2818 | Example 1: 2819 | Input: s = "abc", t = "ahbgdc" 2820 | Output: true 2821 | 2822 | Example 2: 2823 | Input: s = "axc", t = "ahbgdc" 2824 | Output: false 2825 | 2826 | Constraints: 2827 | * 0 <= s.length <= 100 2828 | * 0 <= t.length <= 10^4 2829 | * s and t consist only of lowercase English letters. 2830 | 2831 | Follow up: Suppose there are lots of incoming s, say s1, s2, ..., sk where 2832 | k >= 10^9, and you want to check one by one to see if t has its 2833 | subsequence. In this scenario, how would you change your code?*/ 2834 | 2835 | func isSubsequence(s string, t string) bool { 2836 | i := 0 2837 | for j := 0; i < len(s) && j < len(t); j++ { 2838 | if s[i] == t[j] { 2839 | i++ 2840 | } 2841 | } 2842 | return i == len(s) 2843 | } 2844 | 2845 | 2846 | /*401. Binary Watch (Easy) 2847 | A binary watch has 4 LEDs on the top to represent the hours (0-11), and 6 LEDs 2848 | on the bottom to represent the minutes (0-59). Each LED represents a zero or 2849 | one, with the least significant bit on the right. 2850 | * For example, the below binary watch reads "4:51". 2851 | Given an integer turnedOn which represents the number of LEDs that are currently 2852 | on (ignoring the PM), return all possible times the watch could represent. You 2853 | may return the answer in any order. The hour must not contain a leading zero. 2854 | * For example, "01:00" is not valid. It should be "1:00". 2855 | The minute must consist of two digits and may contain a leading zero. 2856 | * For example, "10:2" is not valid. It should be "10:02". 2857 | Example 1: 2858 | Input: turnedOn = 1 2859 | Output: ["0:01","0:02","0:04","0:08","0:16","0:32","1:00","2:00","4:00","8:00"] 2860 | 2861 | Example 2: 2862 | Input: turnedOn = 9 2863 | Output: [] 2864 | 2865 | Constraints: 0 <= turnedOn <= 10*/ 2866 | 2867 | func readBinaryWatch(turnedOn int) []string { 2868 | ans := []string{} 2869 | for h := 0; h < 12; h++ { 2870 | hc := bits.OnesCount(uint(h)) 2871 | for m := 0; m < 60; m++ { 2872 | mc := bits.OnesCount(uint(m)) 2873 | if hc + mc == turnedOn { 2874 | ans = append(ans, fmt.Sprintf("%d:%02d", h, m)) 2875 | } 2876 | } 2877 | } 2878 | return ans 2879 | } 2880 | 2881 | 2882 | /*404. Sum of Left Leaves (Easy) 2883 | Given the root of a binary tree, return the sum of all left leaves. A leaf is a 2884 | node with no children. A left leaf is a leaf that is the left child of another 2885 | node. 2886 | 2887 | Example 1: 2888 | Input: root = [3,9,20,null,null,15,7] 2889 | Output: 24 2890 | Explanation: There are two left leaves in the binary tree, with values 9 and 15 2891 | respectively. 2892 | 2893 | Example 2: 2894 | Input: root = [1] 2895 | Output: 0 2896 | 2897 | Constraints: 2898 | * The number of nodes in the tree is in the range [1, 1000]. 2899 | * -1000 <= Node.val <= 1000*/ 2900 | 2901 | func sumOfLeftLeaves(root *TreeNode) int { 2902 | var dfs func(node *TreeNode, left bool) int 2903 | dfs = func(node *TreeNode, left bool) int { 2904 | if left && node.Left == nil && node.Right == nil { 2905 | return node.Val 2906 | } 2907 | ans := 0 2908 | if node.Left != nil { 2909 | ans += dfs(node.Left, true) 2910 | } 2911 | if node.Right != nil { 2912 | ans += dfs(node.Right, false) 2913 | } 2914 | return ans 2915 | } 2916 | 2917 | return dfs(root, false) 2918 | } 2919 | 2920 | 2921 | /*405. Convert a Number to Hexadecimal (Easy) 2922 | Given a 32-bit integer num, return a string representing its hexadecimal 2923 | representation. For negative integers, two’s complement method is used. All the 2924 | letters in the answer string should be lowercase characters, and there should 2925 | not be any leading zeros in the answer except for the zero itself. Note: You are 2926 | not allowed to use any built-in library method to directly solve this problem. 2927 | 2928 | Example 1: 2929 | Input: num = 26 2930 | Output: "1a" 2931 | 2932 | Example 2: 2933 | Input: num = -1 2934 | Output: "ffffffff" 2935 | 2936 | Constraints: -2^31 <= num <= 2^31 - 1*/ 2937 | 2938 | func toHex(num int) string { 2939 | if num == 0 { 2940 | return "0" 2941 | } 2942 | if num < 0 { 2943 | num += 0xffffffff + 1 2944 | } 2945 | ans := []byte{} 2946 | digits := "0123456789abcdef" 2947 | for ; num > 0; num /= 16 { 2948 | ans = append(ans, digits[num%16]) 2949 | } 2950 | slices.Reverse(ans) 2951 | return string(ans) 2952 | } 2953 | 2954 | 2955 | /*409. Longest Palindrome (Easy) 2956 | Given a string s which consists of lowercase or uppercase letters, return the 2957 | length of the longest palindrome that can be built with those letters. Letters 2958 | are case sensitive, for example, "Aa" is not considered a palindrome. 2959 | 2960 | Example 1: 2961 | Input: s = "abccccdd" 2962 | Output: 7 2963 | Explanation: One longest palindrome that can be built is "dccaccd", whose length 2964 | is 7. 2965 | 2966 | Example 2: 2967 | Input: s = "a" 2968 | Output: 1 2969 | Explanation: The longest palindrome that can be built is "a", whose length is 1. 2970 | 2971 | Constraints: 2972 | * 1 <= s.length <= 2000 2973 | * s consists of lowercase and/or uppercase English letters only.*/ 2974 | 2975 | func longestPalindrome(s string) int { 2976 | freq := map[rune]int{} 2977 | for _, ch := range s { 2978 | freq[ch]++ 2979 | } 2980 | ans := 0 2981 | for _, x := range freq { 2982 | ans += x/2*2 2983 | if ans & 1 == 0 && x & 1 == 1 { 2984 | ans++ 2985 | } 2986 | } 2987 | return ans 2988 | } 2989 | 2990 | 2991 | /*412. Fizz Buzz (Easy) 2992 | Given an integer n, return a string array answer (1-indexed) where: 2993 | * answer[i] == "FizzBuzz" if i is divisible by 3 and 5. 2994 | * answer[i] == "Fizz" if i is divisible by 3. 2995 | * answer[i] == "Buzz" if i is divisible by 5. 2996 | * answer[i] == i (as a string) if none of the above conditions are true. 2997 | 2998 | Example 1: 2999 | Input: n = 3 3000 | Output: ["1","2","Fizz"] 3001 | 3002 | Example 2: 3003 | Input: n = 5 3004 | Output: ["1","2","Fizz","4","Buzz"] 3005 | 3006 | Example 3: 3007 | Input: n = 15 3008 | Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"] 3009 | 3010 | Constraints: 1 <= n <= 10^4*/ 3011 | 3012 | func fizzBuzz(n int) []string { 3013 | ans := []string{} 3014 | for x := 1; x <= n; x++ { 3015 | var elem string 3016 | // naked switch 3017 | switch { 3018 | case x % 3 == 0 && x % 5 == 0: 3019 | elem = "FizzBuzz" 3020 | case x % 3 == 0: 3021 | elem = "Fizz" 3022 | case x % 5 == 0: 3023 | elem = "Buzz" 3024 | default: 3025 | elem = strconv.Itoa(x) 3026 | } 3027 | ans = append(ans, elem) 3028 | } 3029 | return ans 3030 | } 3031 | 3032 | 3033 | /*415. Add Strings (Easy) 3034 | Given two non-negative integers, num1 and num2 represented as string, return the 3035 | sum of num1 and num2 as a string. You must solve the problem without using any 3036 | built-in library for handling large integers (such as BigInteger). You must also 3037 | not convert the inputs to integers directly. 3038 | 3039 | Example 1: 3040 | Input: num1 = "11", num2 = "123" 3041 | Output: "134" 3042 | 3043 | Example 2: 3044 | Input: num1 = "456", num2 = "77" 3045 | Output: "533" 3046 | 3047 | Example 3: 3048 | Input: num1 = "0", num2 = "0" 3049 | Output: "0" 3050 | 3051 | Constraints: 3052 | * 1 <= num1.length, num2.length <= 10^4 3053 | * num1 and num2 consist of only digits. 3054 | * num1 and num2 don't have any leading zeros except for the zero itself.*/ 3055 | 3056 | func addStrings(num1 string, num2 string) string { 3057 | n1, n2 := len(num1), len(num2) 3058 | ans := []byte{} 3059 | carry := 0 3060 | for i := 0; i < n1 || i < n2 || carry > 0; i++ { 3061 | if i < n1 { 3062 | carry += int(num1[n1-i-1] - '0') 3063 | } 3064 | if i < n2 { 3065 | carry += int(num2[n2-i-1] - '0') 3066 | } 3067 | ans = append(ans, byte(carry%10 + '0')) 3068 | carry /= 10 3069 | } 3070 | slices.Reverse(ans) 3071 | return string(ans) 3072 | } 3073 | 3074 | 3075 | /*434. Number of Segments in a String (Easy) 3076 | Given a string s, return the number of segments in the string. A segment is 3077 | defined to be a contiguous sequence of non-space characters. 3078 | 3079 | Example 1: 3080 | Input: s = "Hello, my name is John" 3081 | Output: 5 3082 | Explanation: The five segments are ["Hello,", "my", "name", "is", "John"] 3083 | 3084 | Example 2: 3085 | Input: s = "Hello" 3086 | Output: 1 3087 | 3088 | Constraints: 3089 | * 0 <= s.length <= 300 3090 | * s consists of lowercase and uppercase English letters, digits, or one of the 3091 | following characters "!@#$%^&*()_+-=',.:". 3092 | * The only space character in s is ' '.*/ 3093 | 3094 | func countSegments(s string) int { 3095 | return len(strings.Fields(s)) 3096 | } 3097 | 3098 | 3099 | /*441. Arranging Coins (Easy) 3100 | You have n coins and you want to build a staircase with these coins. The 3101 | staircase consists of k rows where the ith row has exactly i coins. The last row 3102 | of the staircase may be incomplete. Given the integer n, return the number of 3103 | complete rows of the staircase you will build. 3104 | 3105 | Example 1: 3106 | Input: n = 5 3107 | Output: 2 3108 | Explanation: Because the 3rd row is incomplete, we return 2. 3109 | 3110 | Example 2: 3111 | Input: n = 8 3112 | Output: 3 3113 | Explanation: Because the 4th row is incomplete, we return 3. 3114 | 3115 | Constraints: 1 <= n <= 2^31 - 1*/ 3116 | 3117 | func arrangeCoins(n int) int { 3118 | return int((math.Sqrt(1+float64(8*n))-1)/2) 3119 | } 3120 | 3121 | 3122 | /*448. Find All Numbers Disappeared in an Array (Easy) 3123 | Given an array nums of n integers where nums[i] is in the range [1, n], return 3124 | an array of all the integers in the range [1, n] that do not appear in nums. 3125 | 3126 | Example 1: 3127 | Input: nums = [4,3,2,7,8,2,3,1] 3128 | Output: [5,6] 3129 | 3130 | Example 2: 3131 | Input: nums = [1,1] 3132 | Output: [2] 3133 | 3134 | Constraints: 3135 | * n == nums.length 3136 | * 1 <= n <= 10^5 3137 | * 1 <= nums[i] <= n 3138 | 3139 | Follow up: Could you do it without extra space and in O(n) runtime? You may 3140 | assume the returned list does not count as extra space.*/ 3141 | 3142 | func findDisappearedNumbers(nums []int) []int { 3143 | for _, x := range nums { 3144 | x = int(math.Abs(float64(x))) 3145 | if nums[x-1] > 0 { 3146 | nums[x-1] *= -1 3147 | } 3148 | } 3149 | k := 0 3150 | for i, x := range nums { 3151 | if x >= 0 { 3152 | nums[k] = i+1 3153 | k++ 3154 | } 3155 | } 3156 | return nums[:k] 3157 | } 3158 | 3159 | 3160 | /*455. Assign Cookies (Easy) 3161 | Assume you are an awesome parent and want to give your children some cookies. 3162 | But, you should give each child at most one cookie. Each child i has a greed 3163 | factor g[i], which is the minimum size of a cookie that the child will be 3164 | content with; and each cookie j has a size s[j]. If s[j] >= g[i], we can assign 3165 | the cookie j to the child i, and the child i will be content. Your goal is to 3166 | maximize the number of your content children and output the maximum number. 3167 | 3168 | Example 1: 3169 | Input: g = [1,2,3], s = [1,1] 3170 | Output: 1 3171 | Explanation: You have 3 children and 2 cookies. The greed factors of 3 children 3172 | are 1, 2, 3. And even though you have 2 cookies, since their size 3173 | is both 1, you could only make the child whose greed factor is 1 3174 | content. You need to output 1. 3175 | 3176 | Example 2: 3177 | Input: g = [1,2], s = [1,2,3] 3178 | Output: 2 3179 | Explanation: You have 2 children and 3 cookies. The greed factors of 2 children 3180 | are 1, 2. You have 3 cookies and their sizes are big enough to 3181 | gratify all of the children, You need to output 2. 3182 | 3183 | Constraints: 3184 | * 1 <= g.length <= 3 * 10^4 3185 | * 0 <= s.length <= 3 * 10^4 3186 | * 1 <= g[i], s[j] <= 2^31 - 1 3187 | 3188 | Note: This question is the same as 2410: Maximum Matching of Players With 3189 | Trainers.*/ 3190 | 3191 | func findContentChildren(g []int, s []int) int { 3192 | sort.Ints(g) 3193 | sort.Ints(s) 3194 | k := 0 3195 | for _, v := range s { 3196 | if k < len(g) && g[k] <= v { 3197 | k++ 3198 | } 3199 | } 3200 | return k 3201 | } 3202 | 3203 | 3204 | /*459. Repeated Substring Pattern (Easy) 3205 | Given a string s, check if it can be constructed by taking a substring of it and 3206 | appending multiple copies of the substring together. 3207 | 3208 | Example 1: 3209 | Input: s = "abab" 3210 | Output: true 3211 | Explanation: It is the substring "ab" twice. 3212 | 3213 | Example 2: 3214 | Input: s = "aba" 3215 | Output: false 3216 | 3217 | Example 3: 3218 | Input: s = "abcabcabcabc" 3219 | Output: true 3220 | Explanation: It is the substring "abc" four times or the substring "abcabc" 3221 | twice. 3222 | 3223 | Constraints: 3224 | * 1 <= s.length <= 10^4 3225 | * s consists of lowercase English letters.*/ 3226 | 3227 | func repeatedSubstringPattern(s string) bool { 3228 | n := len(s) 3229 | lps := []int{0} 3230 | k := 0 3231 | for i := 1; i < n; i++ { 3232 | for k > 0 && s[k] != s[i] { 3233 | k = lps[k-1] 3234 | } 3235 | if s[k] == s[i] { 3236 | k++ 3237 | } 3238 | lps = append(lps, k) 3239 | } 3240 | return lps[n-1] > 0 && n % (n - lps[n-1]) == 0 3241 | } 3242 | 3243 | 3244 | /*461. Hamming Distance (Easy) 3245 | The Hamming distance between two integers is the number of positions at which 3246 | the corresponding bits are different. Given two integers x and y, return the 3247 | Hamming distance between them. 3248 | 3249 | Example 1: 3250 | Input: x = 1, y = 4 3251 | Output: 2 3252 | Explanation: 1 (0 0 0 1) 3253 | 4 (0 1 0 0) 3254 | ↑ ↑ 3255 | The above arrows point to positions where the corresponding bits 3256 | are different. 3257 | 3258 | Example 2: 3259 | Input: x = 3, y = 1 3260 | Output: 1 3261 | 3262 | Constraints: 0 <= x, y <= 2^31 - 1 3263 | 3264 | Note: This question is the same as 2220: Minimum Bit Flips to Convert Number.*/ 3265 | 3266 | func hammingDistance(x int, y int) int { 3267 | return bits.OnesCount(uint(x ^ y)) 3268 | } 3269 | 3270 | 3271 | /*463. Island Perimeter (Easy) 3272 | You are given row x col grid representing a map where grid[i][j] = 1 represents 3273 | land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/ 3274 | vertically (not diagonally). The grid is completely surrounded by water, and 3275 | there is exactly one island (i.e., one or more connected land cells). The island 3276 | doesn't have "lakes", meaning the water inside isn't connected to the water 3277 | around the island. One cell is a square with side length 1. The grid is 3278 | rectangular, width and height don't exceed 100. Determine the perimeter of the 3279 | island. 3280 | 3281 | Example 1: 3282 | Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] 3283 | Output: 16 3284 | Explanation: The perimeter is the 16 yellow stripes in the image above. 3285 | 3286 | Example 2: 3287 | Input: grid = [[1]] 3288 | Output: 4 3289 | 3290 | Example 3: 3291 | Input: grid = [[1,0]] 3292 | Output: 4 3293 | 3294 | Constraints: 3295 | * row == grid.length 3296 | * col == grid[i].length 3297 | * 1 <= row, col <= 100 3298 | * grid[i][j] is 0 or 1. 3299 | * There is exactly one island in grid.*/ 3300 | 3301 | func islandPerimeter(grid [][]int) int { 3302 | m, n := len(grid), len(grid[0]) 3303 | ans := 0 3304 | for i := 0; i < m; i++ { 3305 | for j := 0; j < n; j++ { 3306 | if grid[i][j] == 1 { 3307 | ans += 4 3308 | if i > 0 && grid[i-1][j] == 1 { ans -= 2 } 3309 | if j > 0 && grid[i][j-1] == 1 { ans -= 2 } 3310 | } 3311 | } 3312 | } 3313 | return ans 3314 | } 3315 | 3316 | 3317 | /*476. Number Complement (Easy) 3318 | The complement of an integer is the integer you get when you flip all the 0's to 3319 | 1's and all the 1's to 0's in its binary representation. For example, The 3320 | integer 5 is "101" in binary and its complement is "010" which is the integer 2. 3321 | Given an integer num, return its complement. 3322 | 3323 | Example 1: 3324 | Input: num = 5 3325 | Output: 2 3326 | Explanation: The binary representation of 5 is 101 (no leading zero bits), and 3327 | its complement is 010. So you need to output 2. 3328 | 3329 | Example 2: 3330 | Input: num = 1 3331 | Output: 0 3332 | Explanation: The binary representation of 1 is 1 (no leading zero bits), and its 3333 | complement is 0. So you need to output 0. 3334 | 3335 | Constraints: 1 <= num < 2^31 3336 | 3337 | Note: This question is the same as 1009: 3338 | https://leetcode.com/problems/complement-of-base-10-integer/*/ 3339 | 3340 | func findComplement(num int) int { 3341 | m := 1 << bits.Len(uint(num))-1 3342 | return m ^ num 3343 | } 3344 | 3345 | 3346 | /*482. License Key Formatting (Easy) 3347 | You are given a license key represented as a string s that consists of only 3348 | alphanumeric characters and dashes. The string is separated into n + 1 groups by 3349 | n dashes. You are also given an integer k. We want to reformat the string s such 3350 | that each group contains exactly k characters, except for the first group, which 3351 | could be shorter than k but still must contain at least one character. 3352 | Furthermore, there must be a dash inserted between two groups, and you should 3353 | convert all lowercase letters to uppercase. Return the reformatted license key. 3354 | 3355 | Example 1: 3356 | Input: s = "5F3Z-2e-9-w", k = 4 3357 | Output: "5F3Z-2E9W" 3358 | Explanation: The string s has been split into two parts, each part has 4 3359 | characters. Note that the two extra dashes are not needed and can 3360 | be removed. 3361 | 3362 | Example 2: 3363 | Input: s = "2-5g-3-J", k = 2 3364 | Output: "2-5G-3J" 3365 | Explanation: The string s has been split into three parts, each part has 2 3366 | characters except the first part as it could be shorter as 3367 | mentioned above. 3368 | 3369 | Constraints: 3370 | * 1 <= s.length <= 10^5 3371 | * s consists of English letters, digits, and dashes '-'. 3372 | * 1 <= k <= 10^4*/ 3373 | 3374 | func licenseKeyFormatting(s string, k int) string { 3375 | s = strings.ToUpper(strings.Replace(s, "-", "", -1)) 3376 | ans := []string{} 3377 | i := 0 3378 | if r := len(s)%k; r != 0 { 3379 | ans = append(ans, s[:r]) 3380 | i = r 3381 | } 3382 | for ; i < len(s); i += k { 3383 | ans = append(ans, s[i:i+k]) 3384 | } 3385 | return strings.Join(ans, "-") 3386 | } 3387 | 3388 | 3389 | /*485. Max Consecutive Ones (Easy) 3390 | Given a binary array nums, return the maximum number of consecutive 1's in the 3391 | array. 3392 | 3393 | Example 1: 3394 | Input: nums = [1,1,0,1,1,1] 3395 | Output: 3 3396 | Explanation: The first two digits or the last three digits are consecutive 1s. 3397 | The maximum number of consecutive 1s is 3. 3398 | 3399 | Example 2: 3400 | Input: nums = [1,0,1,1,0,1] 3401 | Output: 2 3402 | 3403 | Constraints: 3404 | * 1 <= nums.length <= 10^5 3405 | * nums[i] is either 0 or 1.*/ 3406 | 3407 | func findMaxConsecutiveOnes(nums []int) int { 3408 | ans, cnt := 0, 0 3409 | for _, x := range nums { 3410 | if x == 0 { 3411 | cnt = 0 3412 | } else { 3413 | cnt++ 3414 | ans = max(ans, cnt) 3415 | } 3416 | } 3417 | return ans 3418 | } 3419 | 3420 | 3421 | /*492. Construct the Rectangle (Easy) 3422 | A web developer needs to know how to design a web page's size. So, given a 3423 | specific rectangular web page’s area, your job by now is to design a rectangular 3424 | web page, whose length L and width W satisfy the following requirements: 3425 | 1 The area of the rectangular web page you designed must equal to the given 3426 | target area. 3427 | 2 The width W should not be larger than the length L, which means L >= W. 3428 | 3 The difference between length L and width W should be as small as possible. 3429 | Return an array [L, W] where L and W are the length and width of the web page 3430 | you designed in sequence. 3431 | 3432 | Example 1: 3433 | Input: area = 4 3434 | Output: [2,2] 3435 | Explanation: The target area is 4, and all the possible ways to construct it are 3436 | [1,4], [2,2], [4,1]. But according to requirement 2, [1,4] is 3437 | illegal; according to requirement 3, [4,1] is not optimal compared 3438 | to [2,2]. So the length L is 2, and the width W is 2. 3439 | 3440 | Example 2: 3441 | Input: area = 37 3442 | Output: [37,1] 3443 | 3444 | Example 3: 3445 | Input: area = 122122 3446 | Output: [427,286] 3447 | 3448 | Constraints: 1 <= area <= 10^7*/ 3449 | 3450 | func constructRectangle(area int) []int { 3451 | for w := int(math.Sqrt(float64(area)));; w-- { 3452 | if area % w == 0 { 3453 | return []int{area / w, w} 3454 | } 3455 | } 3456 | } 3457 | 3458 | 3459 | /*495. Teemo Attacking (Easy) 3460 | Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo 3461 | attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, 3462 | an attack at second t will mean Ashe is poisoned during the inclusive time 3463 | interval [t, t + duration - 1]. If Teemo attacks again before the poison effect 3464 | ends, the timer for it is reset, and the poison effect will end duration seconds 3465 | after the new attack. You are given a non-decreasing integer array timeSeries, 3466 | where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and 3467 | an integer duration. Return the total number of seconds that Ashe is poisoned. 3468 | 3469 | Example 1: 3470 | Input: timeSeries = [1,4], duration = 2 3471 | Output: 4 3472 | Explanation: Teemo's attacks on Ashe go as follows: 3473 | - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 3474 | and 2. 3475 | - At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 3476 | and 5. 3477 | Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in 3478 | total. 3479 | 3480 | Example 2: 3481 | Input: timeSeries = [1,2], duration = 2 3482 | Output: 3 3483 | Explanation: Teemo's attacks on Ashe go as follows: 3484 | - At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 3485 | and 2. 3486 | - At second 2 however, Teemo attacks again and resets the poison 3487 | timer. Ashe is poisoned for seconds 2 and 3. 3488 | Ashe is poisoned for seconds 1, 2, and 3, which is 3 seconds in 3489 | total. 3490 | 3491 | Constraints: 3492 | * 1 <= timeSeries.length <= 10^4 3493 | * 0 <= timeSeries[i], duration <= 10^7 3494 | * timeSeries is sorted in non-decreasing order.*/ 3495 | 3496 | func findPoisonedDuration(timeSeries []int, duration int) int { 3497 | ans := 0 3498 | for i, x := range timeSeries { 3499 | if i+1 < len(timeSeries) { 3500 | ans += min(duration, timeSeries[i+1] - x) 3501 | } else { 3502 | ans += duration 3503 | } 3504 | } 3505 | return ans 3506 | } 3507 | 3508 | 3509 | /*496. Next Greater Element I (Easy) 3510 | The next greater element of some element x in an array is the first greater 3511 | element that is to the right of x in the same array. You are given two distinct 3512 | 0-indexed integer arrays nums1 and nums2, where nums1 is a subset of nums2. For 3513 | each 0 <= i < nums1.length, find the index j such that nums1[i] == nums2[j] and 3514 | determine the next greater element of nums2[j] in nums2. If there is no next 3515 | greater element, then the answer for this query is -1. Return an array ans of 3516 | length nums1.length such that ans[i] is the next greater element as described 3517 | above. 3518 | 3519 | Example 1: 3520 | Input: nums1 = [4,1,2], nums2 = [1,3,4,2] 3521 | Output: [-1,3,-1] 3522 | Explanation: The next greater element for each value of nums1 is as follows: 3523 | - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater 3524 | element, so the answer is -1. 3525 | - 1 is underlined in nums2 = [1,3,4,2]. The next greater element 3526 | is 3. 3527 | - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater 3528 | element, so the answer is -1. 3529 | 3530 | Example 2: 3531 | Input: nums1 = [2,4], nums2 = [1,2,3,4] 3532 | Output: [3,-1] 3533 | Explanation: The next greater element for each value of nums1 is as follows: 3534 | - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3535 | 3. 3536 | - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater 3537 | element, so the answer is -1. 3538 | 3539 | Constraints: 3540 | * 1 <= nums1.length <= nums2.length <= 1000 3541 | * 0 <= nums1[i], nums2[i] <= 10^4 3542 | * All integers in nums1 and nums2 are unique. 3543 | * All the integers of nums1 also appear in nums2. 3544 | 3545 | Follow up: Could you find an O(nums1.length + nums2.length) solution?*/ 3546 | 3547 | func nextGreaterElement(nums1 []int, nums2 []int) []int { 3548 | stack := []int{} 3549 | greater := map[int]int{} 3550 | for _, x := range nums2 { 3551 | for sz := len(stack); sz > 0 && stack[sz-1] < x; sz-- { 3552 | last := stack[sz-1] 3553 | stack = stack[:sz-1] 3554 | greater[last] = x 3555 | } 3556 | stack = append(stack, x) 3557 | } 3558 | ans := []int{} 3559 | for _, x := range nums1 { 3560 | if val, ok := greater[x]; ok { 3561 | ans = append(ans, val) 3562 | } else { 3563 | ans = append(ans, -1) 3564 | } 3565 | } 3566 | return ans 3567 | } 3568 | 3569 | 3570 | /*500. Keyboard Row (Easy) 3571 | Given an array of strings words, return the words that can be typed using 3572 | letters of the alphabet on only one row of American keyboard like the image 3573 | below. Note that the strings are case-insensitive, both lowercased and 3574 | uppercased of the same letter are treated as if they are at the same row. In the 3575 | American keyboard: 3576 | * the first row consists of the characters "qwertyuiop", 3577 | * the second row consists of the characters "asdfghjkl", and 3578 | * the third row consists of the characters "zxcvbnm". 3579 | 3580 | Example 1: 3581 | Input: words = ["Hello","Alaska","Dad","Peace"] 3582 | Output: ["Alaska","Dad"] 3583 | Explanation: Both "a" and "A" are in the 2nd row of the American keyboard due to 3584 | case insensitivity. 3585 | 3586 | Example 2: 3587 | Input: words = ["omk"] 3588 | Output: [] 3589 | 3590 | Example 3: 3591 | Input: words = ["adsdf","sfd"] 3592 | Output: ["adsdf","sfd"] 3593 | 3594 | Constraints: 3595 | * 1 <= words.length <= 20 3596 | * 1 <= words[i].length <= 100 3597 | * words[i] consists of English letters (both lowercase and uppercase).*/ 3598 | 3599 | func findWords(words []string) []string { 3600 | rows := []string{"qwertyuiop", "asdfghjkl", "zxcvbnm"} 3601 | loc := [26]int{} 3602 | for i, row := range rows { 3603 | for _, ch := range row { 3604 | loc[ch - 'a'] = i 3605 | } 3606 | } 3607 | ans := []string{} 3608 | for _, word := range words { 3609 | val := -1 3610 | for _, ch := range strings.ToLower(word) { 3611 | if val != -1 && val != loc[ch - 'a'] { 3612 | val = -1 3613 | break 3614 | } 3615 | val = loc[ch - 'a'] 3616 | } 3617 | if val >= 0 { 3618 | ans = append(ans, word) 3619 | } 3620 | } 3621 | return ans 3622 | } 3623 | 3624 | 3625 | /*501. Find Mode in Binary Search Tree (Easy) 3626 | Given the root of a binary search tree (BST) with duplicates, return all the 3627 | mode(s) (i.e., the most frequently occurred element) in it. If the tree has more 3628 | than one mode, return them in any order. Assume a BST is defined as follows: 3629 | * The left subtree of a node contains only nodes with keys less than or equal to 3630 | the node's key. 3631 | * The right subtree of a node contains only nodes with keys greater than or 3632 | equal to the node's key. 3633 | * Both the left and right subtrees must also be binary search trees. 3634 | 3635 | Example 1: 3636 | Input: root = [1,null,2,2] 3637 | Output: [2] 3638 | 3639 | Example 2: 3640 | Input: root = [0] 3641 | Output: [0] 3642 | 3643 | Constraints: 3644 | * The number of nodes in the tree is in the range [1, 10^4]. 3645 | * -10^5 <= Node.val <= 10^5 3646 | 3647 | Follow up: Could you do that without using any extra space? (Assume that the 3648 | implicit stack space incurred due to recursion does not count).*/ 3649 | 3650 | func findMode(root *TreeNode) []int { 3651 | ans := []int{} 3652 | cnt, most, prev := 0, 0, 0 3653 | node := root 3654 | stack := []*TreeNode{} 3655 | for node != nil || len(stack) > 0 { 3656 | if node != nil { 3657 | stack = append(stack, node) 3658 | node = node.Left 3659 | } else { 3660 | node = stack[len(stack)-1] 3661 | stack = stack[:len(stack)-1] 3662 | if cnt > 0 && prev != node.Val { cnt = 0 } 3663 | cnt++ 3664 | if cnt >= most { 3665 | if cnt > most { ans, most = nil, cnt } 3666 | ans = append(ans, node.Val) 3667 | } 3668 | prev = node.Val 3669 | node = node.Right 3670 | } 3671 | } 3672 | return ans 3673 | } 3674 | 3675 | 3676 | /*504. Base 7 (Easy) 3677 | Given an integer num, return a string of its base 7 representation. 3678 | 3679 | Example 1: 3680 | Input: num = 100 3681 | Output: "202" 3682 | 3683 | Example 2: 3684 | Input: num = -7 3685 | Output: "-10" 3686 | 3687 | Constraints: -10^7 <= num <= 10^7*/ 3688 | 3689 | func convertToBase7(num int) string { 3690 | return strconv.FormatInt(int64(num), 7) 3691 | } 3692 | 3693 | 3694 | /*506. Relative Ranks (Easy) 3695 | You are given an integer array score of size n, where score[i] is the score of 3696 | the ith athlete in a competition. All the scores are guaranteed to be unique. 3697 | The athletes are placed based on their scores, where the 1st place athlete has 3698 | the highest score, the 2nd place athlete has the 2nd highest score, and so on. 3699 | The placement of each athlete determines their rank: 3700 | * The 1st place athlete's rank is "Gold Medal". 3701 | * The 2nd place athlete's rank is "Silver Medal". 3702 | * The 3rd place athlete's rank is "Bronze Medal". 3703 | * For the 4th place to the nth place athlete, their rank is their placement 3704 | number (i.e., the xth place athlete's rank is "x"). 3705 | Return an array answer of size n where answer[i] is the rank of the ith athlete. 3706 | 3707 | Example 1: 3708 | Input: score = [5,4,3,2,1] 3709 | Output: ["Gold Medal","Silver Medal","Bronze Medal","4","5"] 3710 | Explanation: The placements are [1st, 2nd, 3rd, 4th, 5th]. 3711 | 3712 | Example 2: 3713 | Input: score = [10,3,8,9,4] 3714 | Output: ["Gold Medal","5","Bronze Medal","Silver Medal","4"] 3715 | Explanation: The placements are [1st, 5th, 3rd, 2nd, 4th]. 3716 | 3717 | Constraints: 3718 | * n == score.length 3719 | * 1 <= n <= 10^4 3720 | * 0 <= score[i] <= 10^6 3721 | * All the values in score are unique.*/ 3722 | 3723 | func findRelativeRanks(score []int) []string { 3724 | aug := [][]int{} 3725 | for i, x := range score { 3726 | aug = append(aug, []int{i, x}) 3727 | } 3728 | sort.Slice(aug, func(i, j int) bool { 3729 | return aug[i][1] > aug[j][1] 3730 | }) 3731 | ans := make([]string, len(score)) 3732 | for k, val := range aug { 3733 | elem := "" 3734 | switch k { 3735 | case 0: elem = "Gold Medal" 3736 | case 1: elem = "Silver Medal" 3737 | case 2: elem = "Bronze Medal" 3738 | default: elem = strconv.Itoa(k+1) 3739 | } 3740 | ans[val[0]] = elem 3741 | } 3742 | return ans 3743 | } 3744 | 3745 | 3746 | /*507. Perfect Number (Easy) 3747 | A perfect number is a positive integer that is equal to the sum of its positive 3748 | divisors, excluding the number itself. A divisor of an integer x is an integer 3749 | that can divide x evenly. Given an integer n, return true if n is a perfect 3750 | number, otherwise return false. 3751 | 3752 | Example 1: 3753 | Input: num = 28 3754 | Output: true 3755 | Explanation: 28 = 1 + 2 + 4 + 7 + 14 3756 | 1, 2, 4, 7, and 14 are all divisors of 28. 3757 | 3758 | Example 2: 3759 | Input: num = 7 3760 | Output: false 3761 | 3762 | Constraints: 1 <= num <= 10^8*/ 3763 | 3764 | func checkPerfectNumber(num int) bool { 3765 | total := 0 3766 | for x := 1; x*x <= num; x++ { 3767 | if num % x == 0 { 3768 | total += x + num/x 3769 | } 3770 | } 3771 | return 1 < num && total == 2*num 3772 | } 3773 | 3774 | 3775 | /*509. Fibonacci Number (Easy) 3776 | The Fibonacci numbers, commonly denoted F(n) form a sequence, called the 3777 | Fibonacci sequence, such that each number is the sum of the two preceding ones, 3778 | starting from 0 and 1. That is, 3779 | F(0) = 0, F(1) = 1 3780 | F(n) = F(n - 1) + F(n - 2), for n > 1. 3781 | Given n, calculate F(n). 3782 | 3783 | Example 1: 3784 | Input: n = 2 3785 | Output: 1 3786 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1. 3787 | 3788 | Example 2: 3789 | Input: n = 3 3790 | Output: 2 3791 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2. 3792 | 3793 | Example 3: 3794 | Input: n = 4 3795 | Output: 3 3796 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3. 3797 | 3798 | Constraints: 0 <= n <= 30*/ 3799 | 3800 | func fib(n int) int { 3801 | if n <= 1 { 3802 | return n 3803 | } 3804 | f0, f1 := 0, 1 3805 | for i := 2; i <= n; i++ { 3806 | f0, f1 = f1, f0+f1 3807 | } 3808 | return f1 3809 | } 3810 | 3811 | 3812 | /*520. Detect Capital (Easy) 3813 | We define the usage of capitals in a word to be right when one of the following 3814 | cases holds: 3815 | * All letters in this word are capitals, like "USA". 3816 | * All letters in this word are not capitals, like "leetcode". 3817 | * Only the first letter in this word is capital, like "Google". 3818 | Given a string word, return true if the usage of capitals in it is right. 3819 | 3820 | Example 1: 3821 | Input: word = "USA" 3822 | Output: true 3823 | 3824 | Example 2: 3825 | Input: word = "FlaG" 3826 | Output: false 3827 | 3828 | Constraints: 3829 | * 1 <= word.length <= 100 3830 | * word consists of lowercase and uppercase English letters.*/ 3831 | 3832 | func detectCapitalUse(word string) bool { 3833 | return word == strings.ToUpper(word) || 3834 | word == strings.ToLower(word) || 3835 | word == strings.ToUpper(word[:1]) + strings.ToLower(word[1:]) 3836 | } 3837 | 3838 | 3839 | /*3492. Maximum Containers on a Ship (Easy) 3840 | You are given a positive integer n representing an n x n cargo deck on a 3841 | ship. Each cell on the deck can hold one container with a weight of exactly 3842 | w. However, the total weight of all containers, if loaded onto the deck, 3843 | must not exceed the ship's maximum weight capacity, maxWeight. Return the 3844 | maximum number of containers that can be loaded onto the ship. 3845 | 3846 | Example 1: 3847 | Input: n = 2, w = 3, maxWeight = 15 3848 | Output: 4 3849 | Explanation: The deck has 4 cells, and each container weighs 3. The total 3850 | weight of loading all containers is 12, which does not exceed 3851 | maxWeight. 3852 | 3853 | Example 2: 3854 | Input: n = 3, w = 5, maxWeight = 20 3855 | Output: 4 3856 | Explanation: The deck has 9 cells, and each container weighs 5. The maximum 3857 | number of containers that can be loaded without exceeding 3858 | maxWeight is 4. 3859 | 3860 | Constraints: 3861 | * 1 <= n <= 1000 3862 | * 1 <= w <= 1000 3863 | * 1 <= maxWeight <= 10^9*/ 3864 | 3865 | func maxContainers(n int, w int, maxWeight int) int { 3866 | return min(n*n, maxWeight/w) 3867 | } 3868 | 3869 | 3870 | /*3493. Properties Graph (Medium) 3871 | You are given a 2D integer array properties having dimensions n x m and an 3872 | integer k. Define a function intersect(a, b) that returns the number of 3873 | distinct integers common to both arrays a and b. Construct an undirected 3874 | graph where each index i corresponds to properties[i]. There is an edge 3875 | between node i and node j if and only if 3876 | intersect(properties[i], properties[j]) >= k, where i and j are in the range 3877 | [0, n - 1] and i != j. Return the number of connected components in the 3878 | resulting graph. 3879 | 3880 | Example 1: 3881 | Input: properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1 3882 | Output: 3 3883 | Explanation: The graph formed has 3 connected components: 3884 | 3885 | Example 2: 3886 | Input: properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2 3887 | Output: 1 3888 | Explanation: The graph formed has 1 connected component: 3889 | 3890 | Example 3: 3891 | Input: properties = [[1,1],[1,1]], k = 2 3892 | Output: 2 3893 | Explanation: intersect(properties[0], properties[1]) = 1, which is less than 3894 | k. This means there is no edge between properties[0] and 3895 | properties[1] in the graph. 3896 | 3897 | Constraints: 3898 | * 1 <= n == properties.length <= 100 3899 | * 1 <= m == properties[i].length <= 100 3900 | * 1 <= properties[i][j] <= 100 3901 | * 1 <= k <= m*/ 3902 | 3903 | func numberOfComponents(properties [][]int, k int) int { 3904 | n := len(properties) 3905 | ps := []map[int]struct{}{} 3906 | for _, p := range properties { 3907 | elem := map[int]struct{}{} 3908 | for _, x := range p { 3909 | elem[x] = struct{}{} 3910 | } 3911 | ps = append(ps, elem) 3912 | } 3913 | parent := make([]int, n) 3914 | for i := 0; i < n; i++ { 3915 | parent[i] = i 3916 | } 3917 | 3918 | var find func(p int) int 3919 | find = func(p int) int { 3920 | if (p != parent[p]) { 3921 | parent[p] = find(parent[p]) 3922 | } 3923 | return parent[p] 3924 | } 3925 | 3926 | for i := 0; i < n; i++ { 3927 | for j := i+1; j < n; j++ { 3928 | cnt := 0 3929 | for x, _ := range ps[i] { 3930 | if _, ok := ps[j][x]; ok { 3931 | cnt++ 3932 | } 3933 | } 3934 | if cnt >= k { 3935 | parent[find(i)] = find(j) 3936 | } 3937 | } 3938 | } 3939 | freq := map[int]int{} 3940 | for _, x := range parent { 3941 | freq[find(x)]++ 3942 | } 3943 | return len(freq) 3944 | } 3945 | 3946 | 3947 | /*3494. Find the Minimum Amount of Time to Brew Potions (Medium) 3948 | You are given two integer arrays, skill and mana, of length n and m, 3949 | respectively. In a laboratory, n wizards must brew m potions in order. Each 3950 | potion has a mana capacity mana[j] and must pass through all the wizards 3951 | sequentially to be brewed properly. The time taken by the ith wizard on the 3952 | jth potion is timeij = skill[i] * mana[j]. Since the brewing process is 3953 | delicate, a potion must be passed to the next wizard immediately after the 3954 | current wizard completes their work. This means the timing must be 3955 | synchronized so that each wizard begins working on a potion exactly when it 3956 | arrives. Return the minimum amount of time required for the potions to be 3957 | brewed properly. 3958 | 3959 | Example 1: 3960 | Input: skill = [1,5,2,4], mana = [5,1,4,2] 3961 | Output: 110 3962 | Explanation: Potion Number Start time Wizard 0 done by Wizard 1 done by Wizard 2 done by Wizard 3 done by 3963 | 0 0 5 30 40 60 3964 | 1 52 53 58 60 64 3965 | 2 54 58 78 86 102 3966 | 3 86 88 98 102 110 3967 | As an example for why wizard 0 cannot start working on the 1st 3968 | potion before time t = 52, consider the case where the wizards 3969 | started preparing the 1st potion at time t = 50. At time 3970 | t = 58, wizard 2 is done with the 1st potion, but wizard 3 will 3971 | still be working on the 0th potion till time t = 60. 3972 | 3973 | Example 2: 3974 | Input: skill = [1,1,1], mana = [1,1,1] 3975 | Output: 5 3976 | Explanation: - Preparation of the 0th potion begins at time t = 0, and is 3977 | completed by time t = 3. 3978 | - Preparation of the 1st potion begins at time t = 1, and is 3979 | completed by time t = 4. 3980 | - Preparation of the 2nd potion begins at time t = 2, and is 3981 | completed by time t = 5. 3982 | 3983 | Example 3: 3984 | Input: skill = [1,2,3,4], mana = [1,2] 3985 | Output: 21 3986 | 3987 | Constraints: 3988 | * n == skill.length 3989 | * m == mana.length 3990 | * 1 <= n, m <= 5000 3991 | * 1 <= mana[i], skill[i] <= 5000*/ 3992 | 3993 | func minTime(skill []int, mana []int) int64 { 3994 | n, m := len(skill), len(mana) 3995 | dp := make([]int64, n) 3996 | for j := 0; j < m; j++ { 3997 | for i := 0; i < n; i++ { 3998 | if (i > 0) { 3999 | dp[i] = max(dp[i-1], dp[i]) 4000 | } 4001 | dp[i] += int64(skill[i] * mana[j]) 4002 | } 4003 | for i := n-1; i > 0; i-- { 4004 | dp[i-1] = dp[i] - int64(skill[i] * mana[j]) 4005 | } 4006 | } 4007 | return dp[n-1] 4008 | } 4009 | 4010 | 4011 | /*3495. Minimum Operations to Make Array Elements Zero (Hard) 4012 | You are given a 2D array queries, where queries[i] is of the form [l, r]. 4013 | Each queries[i] defines an array of integers nums consisting of elements 4014 | ranging from l to r, both inclusive. In one operation, you can: 4015 | * Select two integers a and b from the array. 4016 | * Replace them with floor(a / 4) and floor(b / 4). 4017 | Your task is to determine the minimum number of operations required to 4018 | reduce all elements of the array to zero for each query. Return the sum of 4019 | the results for all queries. 4020 | 4021 | Example 1: 4022 | Input: queries = [[1,2],[2,4]] 4023 | Output: 3 4024 | Explanation: For queries[0]: 4025 | - The initial array is nums = [1, 2]. 4026 | - In the first operation, select nums[0] and nums[1]. The array 4027 | becomes [0, 0]. 4028 | - The minimum number of operations required is 1. 4029 | For queries[1]: 4030 | - The initial array is nums = [2, 3, 4]. 4031 | - In the first operation, select nums[0] and nums[2]. The array 4032 | becomes [0, 3, 1]. 4033 | - In the second operation, select nums[1] and nums[2]. The 4034 | array becomes [0, 0, 0]. 4035 | - The minimum number of operations required is 2. 4036 | The output is 1 + 2 = 3. 4037 | 4038 | Example 2: 4039 | Input: queries = [[2,6]] 4040 | Output: 4 4041 | Explanation: For queries[0]: 4042 | - The initial array is nums = [2, 3, 4, 5, 6]. 4043 | - In the first operation, select nums[0] and nums[3]. The array 4044 | becomes [0, 3, 4, 1, 6]. 4045 | - In the second operation, select nums[2] and nums[4]. The 4046 | array becomes [0, 3, 1, 1, 1]. 4047 | - In the third operation, select nums[1] and nums[2]. The array 4048 | becomes [0, 0, 0, 1, 1]. 4049 | - In the fourth operation, select nums[3] and nums[4]. The 4050 | array becomes [0, 0, 0, 0, 0]. 4051 | - The minimum number of operations required is 4. 4052 | The output is 4. 4053 | 4054 | Constraints: 4055 | * 1 <= queries.length <= 10^5 4056 | * queries[i].length == 2 4057 | * queries[i] == [l, r] 4058 | * 1 <= l < r <= 10^9*/ 4059 | 4060 | func minOperations(queries [][]int) int64 { 4061 | ans := int64(0) 4062 | for _, q := range queries { 4063 | l, r := q[0], q[1] 4064 | ops := 0 4065 | for p, step := 1, 1; p <= 15; p++ { 4066 | lo := max(step, l) 4067 | hi := min(4*step, r+1) 4068 | if (lo < hi) { 4069 | ops += p * (hi-lo) 4070 | } 4071 | step *= 4 4072 | } 4073 | ans += int64((ops+1)/2) 4074 | } 4075 | return ans 4076 | } 4077 | -------------------------------------------------------------------------------- /leetcode.rs: -------------------------------------------------------------------------------- 1 | /*1. Two Sum (Easy) 2 | Given an array of integers nums and an integer target, return indices of the two 3 | numbers such that they add up to target. You may assume that each input would 4 | have exactly one solution, and you may not use the same element twice. You can 5 | return the answer in any order. 6 | 7 | Example 1: 8 | Input: nums = [2,7,11,15], target = 9 9 | Output: [0,1] 10 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. 11 | 12 | Example 2: 13 | Input: nums = [3,2,4], target = 6 14 | Output: [1,2] 15 | 16 | Example 3: 17 | Input: nums = [3,3], target = 6 18 | Output: [0,1] 19 | 20 | Constraints: 21 | * 2 <= nums.length <= 10^4 22 | * -10^9 <= nums[i] <= 10^9 23 | * -10^9 <= target <= 10^9 24 | * Only one valid answer exists. 25 | 26 | Follow-up: Can you come up with an algorithm that is less than O(n2) time 27 | complexity?*/ 28 | 29 | impl Solution { 30 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 31 | let mut seen = std::collections::HashMap::new(); 32 | for (i, &x) in nums.iter().enumerate() { 33 | let diff = target - x; 34 | if seen.contains_key(&diff) { 35 | let &j = seen.get(&diff).unwrap(); 36 | return vec![j, i as i32]; 37 | } 38 | seen.insert(x, i as i32); 39 | } 40 | panic!(); 41 | } 42 | } 43 | 44 | 45 | /*9. Palindrome Number (Easy) 46 | Given an integer x, return true if x is a palindrome, and false otherwise. 47 | 48 | Example 1: 49 | Input: x = 121 50 | Output: true 51 | Explanation: 121 reads as 121 from left to right and from right to left. 52 | 53 | Example 2: 54 | Input: x = -121 55 | Output: false 56 | Explanation: From left to right, it reads -121. From right to left, it becomes 57 | 121-. Therefore it is not a palindrome. 58 | Example 3: 59 | Input: x = 10 60 | Output: false 61 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 62 | 63 | Constraints: -2^31 <= x <= 2^31 - 1*/ 64 | 65 | impl Solution { 66 | pub fn is_palindrome(x: i32) -> bool { 67 | let s = x.to_string(); 68 | return s == s.chars().rev().collect::(); 69 | } 70 | } 71 | 72 | 73 | /*13. Roman to Integer (Easy) 74 | Roman numerals are represented by seven different symbols: I, V, X, L, C, D and 75 | M. 76 | Symbol Value 77 | I 1 78 | V 5 79 | X 10 80 | L 50 81 | C 100 82 | D 500 83 | M 1000 84 | For example, 2 is written as II in Roman numeral, just two ones added together. 85 | 12 is written as XII, which is simply X + II. The number 27 is written as XXVII, 86 | which is XX + V + II. Roman numerals are usually written largest to smallest 87 | from left to right. However, the numeral for four is not IIII. Instead, the 88 | number four is written as IV. Because the one is before the five we subtract it 89 | making four. The same principle applies to the number nine, which is written as 90 | IX. There are six instances where subtraction is used: 91 | * I can be placed before V (5) and X (10) to make 4 and 9. 92 | * X can be placed before L (50) and C (100) to make 40 and 90. 93 | * C can be placed before D (500) and M (1000) to make 400 and 900. 94 | Given a roman numeral, convert it to an integer. 95 | 96 | Example 1: 97 | Input: s = "III" 98 | Output: 3 99 | Explanation: III = 3. 100 | 101 | Example 2: 102 | Input: s = "LVIII" 103 | Output: 58 104 | Explanation: L = 50, V= 5, III = 3. 105 | 106 | Example 3: 107 | Input: s = "MCMXCIV" 108 | Output: 1994 109 | Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. 110 | 111 | Constraints: 112 | * 1 <= s.length <= 15 113 | * s contains only the characters ('I', 'V', 'X', 'L', 'C', 'D', 'M'). 114 | * It is guaranteed that s is a valid roman numeral in the range [1, 3999].*/ 115 | 116 | impl Solution { 117 | pub fn roman_to_int(s: String) -> i32 { 118 | let map = std::collections::HashMap::from([ 119 | ('I', 1), 120 | ('V', 5), 121 | ('X', 10), 122 | ('L', 50), 123 | ('C', 100), 124 | ('D', 500), 125 | ('M', 1000) 126 | ]); 127 | let mut ans = 0; 128 | let chars: Vec = s.chars().collect(); 129 | for (i, ch) in chars.iter().enumerate() { 130 | let val = map.get(&ch).unwrap(); 131 | if (i+1 < s.len() && val < map.get(&chars[i+1]).unwrap()) { 132 | ans -= val; 133 | } else { 134 | ans += val; 135 | } 136 | } 137 | return ans; 138 | } 139 | } 140 | 141 | 142 | /*14. Longest Common Prefix (Easy) 143 | Write a function to find the longest common prefix string amongst an array of 144 | strings. If there is no common prefix, return an empty string "". 145 | 146 | Example 1: 147 | Input: strs = ["flower","flow","flight"] 148 | Output: "fl" 149 | 150 | Example 2: 151 | Input: strs = ["dog","racecar","car"] 152 | Output: "" 153 | Explanation: There is no common prefix among the input strings. 154 | 155 | Constraints: 156 | * 1 <= strs.length <= 200 157 | * 0 <= strs[i].length <= 200 158 | * strs[i] consists of only lowercase English letters if it is non-empty.*/ 159 | 160 | impl Solution { 161 | pub fn longest_common_prefix(strs: Vec) -> String { 162 | match strs.is_empty() { 163 | true => "".to_string(), 164 | _ => { 165 | strs.iter().skip(1).fold(strs[0].clone(), |acc, x| { 166 | acc 167 | .chars() 168 | .zip(x.chars()) 169 | .take_while(|(x, y)| x == y) 170 | .map(|(x, _)| x) 171 | .collect() 172 | }) 173 | } 174 | } 175 | } 176 | } 177 | 178 | 179 | /*20. Valid Parentheses (Easy) 180 | Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', 181 | determine if the input string is valid. An input string is valid if: 182 | * Open brackets must be closed by the same type of brackets. 183 | * Open brackets must be closed in the correct order. 184 | * Every close bracket has a corresponding open bracket of the same type. 185 | 186 | Example 1: 187 | Input: s = "()" 188 | Output: true 189 | 190 | Example 2: 191 | Input: s = "()[]{}" 192 | Output: true 193 | 194 | Example 3: 195 | Input: s = "(]" 196 | Output: false 197 | 198 | Example 4: 199 | Input: s = "([])" 200 | Output: true 201 | 202 | Constraints: 203 | * 1 <= s.length <= 10^4 204 | * s consists of parentheses only '()[]{}'.*/ 205 | 206 | impl Solution { 207 | pub fn is_valid(s: String) -> bool { 208 | let mut stack = Vec::new(); 209 | for ch in s.chars() { 210 | match ch { 211 | '{' => stack.push('}'), 212 | '(' => stack.push(')'), 213 | '[' => stack.push(']'), 214 | _ => if Some(ch) != stack.pop() { return false }, 215 | } 216 | } 217 | return stack.is_empty(); 218 | } 219 | } 220 | 221 | 222 | /*26. Remove Duplicates from Sorted Array (Easy) 223 | Given an integer array nums sorted in non-decreasing order, remove the 224 | duplicates in-place such that each unique element appears only once. The 225 | relative order of the elements should be kept the same. Then return the number 226 | of unique elements in nums. Consider the number of unique elements of nums to be 227 | k, to get accepted, you need to do the following things: 228 | * Change the array nums such that the first k elements of nums contain the 229 | unique elements in the order they were present in nums initially. The 230 | remaining elements of nums are not important as well as the size of nums. 231 | * Return k. 232 | 233 | Custom Judge: 234 | The judge will test your solution with the following code: 235 | int[] nums = [...]; // Input array 236 | int[] expectedNums = [...]; // The expected answer with correct length 237 | 238 | int k = removeDuplicates(nums); // Calls your implementation 239 | 240 | assert k == expectedNums.length; 241 | for (int i = 0; i < k; i++) { 242 | assert nums[i] == expectedNums[i]; 243 | } 244 | If all assertions pass, then your solution will be accepted. 245 | 246 | Example 1: 247 | Input: nums = [1,1,2] 248 | Output: 2, nums = [1,2,_] 249 | Explanation: Your function should return k = 2, with the first two elements of 250 | nums being 1 and 2 respectively. It does not matter what you leave 251 | beyond the returned k (hence they are underscores). 252 | 253 | Example 2: 254 | Input: nums = [0,0,1,1,1,2,2,3,3,4] 255 | Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] 256 | Explanation: Your function should return k = 5, with the first five elements of 257 | nums being 0, 1, 2, 3, and 4 respectively. It does not matter what 258 | you leave beyond the returned k (hence they are underscores). 259 | 260 | Constraints: 261 | * 1 <= nums.length <= 3 * 10^4 262 | * -100 <= nums[i] <= 100 263 | * nums is sorted in non-decreasing order.*/ 264 | 265 | impl Solution { 266 | pub fn remove_duplicates(nums: &mut Vec) -> i32 { 267 | nums.dedup(); 268 | nums.len() as i32 269 | } 270 | } 271 | 272 | 273 | /*27. Remove Element (Easy) 274 | Given an integer array nums and an integer val, remove all occurrences of val in 275 | nums in-place. The order of the elements may be changed. Then return the number 276 | of elements in nums which are not equal to val. Consider the number of elements 277 | in nums which are not equal to val be k, to get accepted, you need to do the 278 | following things: 279 | * Change the array nums such that the first k elements of nums contain the 280 | elements which are not equal to val. The remaining elements of nums are not 281 | important as well as the size of nums. 282 | * Return k. 283 | 284 | Custom Judge: 285 | The judge will test your solution with the following code: 286 | int[] nums = [...]; // Input array 287 | int val = ...; // Value to remove 288 | int[] expectedNums = [...]; // The expected answer with correct length. 289 | // It is sorted with no values equaling val. 290 | 291 | int k = removeElement(nums, val); // Calls your implementation 292 | 293 | assert k == expectedNums.length; 294 | sort(nums, 0, k); // Sort the first k elements of nums 295 | for (int i = 0; i < actualLength; i++) { 296 | assert nums[i] == expectedNums[i]; 297 | } 298 | If all assertions pass, then your solution will be accepted. 299 | 300 | Example 1: 301 | Input: nums = [3,2,2,3], val = 3 302 | Output: 2, nums = [2,2,_,_] 303 | Explanation: Your function should return k = 2, with the first two elements of 304 | nums being 2. It does not matter what you leave beyond the returned 305 | k (hence they are underscores). 306 | 307 | Example 2: 308 | Input: nums = [0,1,2,2,3,0,4,2], val = 2 309 | Output: 5, nums = [0,1,4,0,3,_,_,_] 310 | Explanation: Your function should return k = 5, with the first five elements of 311 | nums containing 0, 0, 1, 3, and 4. Note that the five elements can 312 | be returned in any order. It does not matter what you leave beyond 313 | the returned k (hence they are underscores). 314 | 315 | Constraints: 316 | * 0 <= nums.length <= 100 317 | * 0 <= nums[i] <= 50 318 | * 0 <= val <= 100*/ 319 | 320 | impl Solution { 321 | pub fn remove_element(nums: &mut Vec, val: i32) -> i32 { 322 | nums.retain(|&x| x != val); 323 | return nums.len() as i32; 324 | } 325 | } 326 | 327 | 328 | /*28. Find the Index of the First Occurrence in a String (Easy) 329 | Given two strings needle and haystack, return the index of the first occurrence 330 | of needle in haystack, or -1 if needle is not part of haystack. 331 | 332 | Example 1: 333 | Input: haystack = "sadbutsad", needle = "sad" 334 | Output: 0 335 | Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, 336 | so we return 0. 337 | 338 | Example 2: 339 | Input: haystack = "leetcode", needle = "leeto" 340 | Output: -1 341 | Explanation: "leeto" did not occur in "leetcode", so we return -1. 342 | 343 | Constraints: 344 | * 1 <= haystack.length, needle.length <= 10^4 345 | * haystack and needle consist of only lowercase English characters.*/ 346 | 347 | impl Solution { 348 | pub fn str_str(haystack: String, needle: String) -> i32 { 349 | return haystack.find(&needle).map(|x| x as i32).unwrap_or(-1); 350 | } 351 | } 352 | 353 | 354 | /*35. Search Insert Position (Easy) 355 | Given a sorted array of distinct integers and a target value, return the index 356 | if the target is found. If not, return the index where it would be if it were 357 | inserted in order. You must write an algorithm with O(log n) runtime complexity. 358 | 359 | Example 1: 360 | Input: nums = [1,3,5,6], target = 5 361 | Output: 2 362 | 363 | Example 2: 364 | Input: nums = [1,3,5,6], target = 2 365 | Output: 1 366 | 367 | Example 3: 368 | Input: nums = [1,3,5,6], target = 7 369 | Output: 4 370 | 371 | Constraints: 372 | * 1 <= nums.length <= 10^4 373 | * -10^4 <= nums[i] <= 10^4 374 | * nums contains distinct values sorted in ascending order. 375 | * -10^4 <= target <= 10^4*/ 376 | 377 | impl Solution { 378 | pub fn search_insert(nums: Vec, target: i32) -> i32 { 379 | return nums.binary_search(&target).unwrap_or_else(|x| x) as i32; 380 | } 381 | } 382 | 383 | 384 | /*58. Length of Last Word (Easy) 385 | Given a string s consisting of words and spaces, return the length of the last 386 | word in the string. A word is a maximal substring consisting of non-space 387 | characters only. 388 | 389 | Example 1: 390 | Input: s = "Hello World" 391 | Output: 5 392 | Explanation: The last word is "World" with length 5. 393 | 394 | Example 2: 395 | Input: s = " fly me to the moon " 396 | Output: 4 397 | Explanation: The last word is "moon" with length 4. 398 | 399 | Example 3: 400 | Input: s = "luffy is still joyboy" 401 | Output: 6 402 | Explanation: The last word is "joyboy" with length 6. 403 | 404 | Constraints: 405 | * 1 <= s.length <= 10^4 406 | * s consists of only English letters and spaces ' '. 407 | * There will be at least one word in s.*/ 408 | 409 | impl Solution { 410 | pub fn length_of_last_word(s: String) -> i32 { 411 | s.split_whitespace() 412 | .last() 413 | .unwrap() 414 | .len() as i32 415 | } 416 | } 417 | 418 | 419 | /*66. Plus One (Easy) 420 | You are given a large integer represented as an integer array digits, where each 421 | digits[i] is the ith digit of the integer. The digits are ordered from most 422 | significant to least significant in left-to-right order. The large integer does 423 | not contain any leading 0's. Increment the large integer by one and return the 424 | resulting array of digits. 425 | 426 | Example 1: 427 | Input: digits = [1,2,3] 428 | Output: [1,2,4] 429 | Explanation: The array represents the integer 123. Incrementing by one gives 430 | 123 + 1 = 124. Thus, the result should be [1,2,4]. 431 | 432 | Example 2: 433 | Input: digits = [4,3,2,1] 434 | Output: [4,3,2,2] 435 | Explanation: The array represents the integer 4321. Incrementing by one gives 436 | 4321 + 1 = 4322. Thus, the result should be [4,3,2,2]. 437 | 438 | Example 3: 439 | Input: digits = [9] 440 | Output: [1,0] 441 | Explanation: The array represents the integer 9. Incrementing by one gives 442 | 9 + 1 = 10. Thus, the result should be [1,0]. 443 | 444 | Constraints: 445 | * 1 <= digits.length <= 100 446 | * 0 <= digits[i] <= 9 447 | * digits does not contain any leading 0's.*/ 448 | 449 | impl Solution { 450 | pub fn plus_one(mut digits: Vec) -> Vec { 451 | for x in digits.iter_mut().rev() { 452 | match *x == 9 { 453 | true => *x = 0, 454 | false => { 455 | *x += 1; 456 | return digits; 457 | } 458 | } 459 | } 460 | digits.insert(0, 1); 461 | return digits; 462 | } 463 | } 464 | 465 | 466 | /*69. Sqrt(x) (Easy) 467 | Given a non-negative integer x, return the square root of x rounded down to the 468 | nearest integer. The returned integer should be non-negative as well. You must 469 | not use any built-in exponent function or operator. 470 | * For example, do not use pow(x, 0.5) in c++ or x ** 0.5 in python. 471 | 472 | Example 1: 473 | Input: x = 4 474 | Output: 2 475 | Explanation: The square root of 4 is 2, so we return 2. 476 | 477 | Example 2: 478 | Input: x = 8 479 | Output: 2 480 | Explanation: The square root of 8 is 2.82842..., and since we round it down to 481 | the nearest integer, 2 is returned. 482 | 483 | Constraints: 0 <= x <= 2^31 - 1*/ 484 | 485 | impl Solution { 486 | pub fn my_sqrt(x: i32) -> i32 { 487 | let x = x as i64; 488 | let mut ans = x; 489 | while ans > 0 && ans > x/ans { 490 | ans = (ans + x/ans)/2; 491 | } 492 | return ans as i32; 493 | } 494 | } 495 | 496 | 497 | /*70. Climbing Stairs (Easy) 498 | You are climbing a staircase. It takes n steps to reach the top. Each time you 499 | can either climb 1 or 2 steps. In how many distinct ways can you climb to the 500 | top? 501 | 502 | Example 1: 503 | Input: n = 2 504 | Output: 2 505 | Explanation: There are two ways to climb to the top. 506 | 1. 1 step + 1 step 507 | 2. 2 steps 508 | 509 | Example 2: 510 | Input: n = 3 511 | Output: 3 512 | Explanation: There are three ways to climb to the top. 513 | 1. 1 step + 1 step + 1 step 514 | 2. 1 step + 2 steps 515 | 3. 2 steps + 1 step 516 | 517 | Constraints: 1 <= n <= 45*/ 518 | 519 | impl Solution { 520 | pub fn climb_stairs(n: i32) -> i32 { 521 | let (mut f0, mut f1) = (0, 1); 522 | for i in 0..n { 523 | (f0, f1) = (f1, f0+f1); 524 | } 525 | return f1; 526 | } 527 | } 528 | 529 | 530 | /*83. Remove Duplicates from Sorted List (Easy) 531 | Given the head of a sorted linked list, delete all duplicates such that each 532 | element appears only once. Return the linked list sorted as well. 533 | 534 | Example 1: 535 | Input: head = [1,1,2] 536 | Output: [1,2] 537 | 538 | Example 2: 539 | Input: head = [1,1,2,3,3] 540 | Output: [1,2,3] 541 | 542 | Constraints: 543 | * The number of nodes in the list is in the range [0, 300]. 544 | * -100 <= Node.val <= 100 545 | * The list is guaranteed to be sorted in ascending order.*/ 546 | 547 | impl Solution { 548 | pub fn delete_duplicates(mut head: Option>) -> Option> { 549 | if (head.is_some()) { 550 | let mut node = head.as_mut().unwrap(); 551 | while let Some(temp) = node.next.as_mut() { 552 | if (node.val == temp.val) { 553 | node.next = temp.next.take(); 554 | } else { 555 | node = node.next.as_mut().unwrap(); 556 | } 557 | } 558 | } 559 | return head; 560 | } 561 | } 562 | 563 | 564 | /*88. Merge Sorted Array (Easy) 565 | You are given two integer arrays nums1 and nums2, sorted in non-decreasing 566 | order, and two integers m and n, representing the number of elements in nums1 567 | and nums2 respectively. Merge nums1 and nums2 into a single array sorted in 568 | non-decreasing order. The final sorted array should not be returned by the 569 | function, but instead be stored inside the array nums1. To accommodate this, 570 | nums1 has a length of m + n, where the first m elements denote the elements that 571 | should be merged, and the last n elements are set to 0 and should be ignored. 572 | nums2 has a length of n. 573 | 574 | Example 1: 575 | Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 576 | Output: [1,2,2,3,5,6] 577 | Explanation: The arrays we are merging are [1,2,3] and [2,5,6]. The result of 578 | the merge is [1,2,2,3,5,6] with the underlined elements coming from 579 | nums1. 580 | 581 | Example 2: 582 | Input: nums1 = [1], m = 1, nums2 = [], n = 0 583 | Output: [1] 584 | Explanation: The arrays we are merging are [1] and []. The result of the merge 585 | is [1]. 586 | 587 | Example 3: 588 | Input: nums1 = [0], m = 0, nums2 = [1], n = 1 589 | Output: [1] 590 | Explanation: The arrays we are merging are [] and [1]. The result of the merge 591 | is [1]. Note that because m = 0, there are no elements in nums1. 592 | The 0 is only there to ensure the merge result can fit in nums1. 593 | 594 | Constraints: 595 | * nums1.length == m + n 596 | * nums2.length == n 597 | * 0 <= m, n <= 200 598 | * 1 <= m + n <= 200 599 | * -10^9 <= nums1[i], nums2[j] <= 10^9 600 | 601 | Follow up: Can you come up with an algorithm that runs in O(m + n) time?*/ 602 | 603 | impl Solution { 604 | pub fn merge(nums1: &mut Vec, m: i32, nums2: &mut Vec, n: i32) { 605 | let (mut m, mut n) = (m as usize, n as usize); 606 | while 0 < n { 607 | if 0 < m && nums1[m-1] >= nums2[n-1] { 608 | nums1[m+n-1] = nums1[m-1]; 609 | m -= 1; 610 | } else { 611 | nums1[m+n-1] = nums2[n-1]; 612 | n -= 1; 613 | } 614 | } 615 | } 616 | } 617 | 618 | 619 | /*94. Binary Tree Inorder Traversal (Easy) 620 | Given the root of a binary tree, return the inorder traversal of its nodes' 621 | values. 622 | 623 | Example 1: 624 | Input: root = [1,null,2,3] 625 | Output: [1,3,2] 626 | Explanation: 627 | 628 | Example 2: 629 | Input: root = [1,2,3,4,5,null,8,null,null,6,7,9] 630 | Output: [4,2,6,5,7,1,3,9,8] 631 | Explanation: 632 | 633 | Example 3: 634 | Input: root = [] 635 | Output: [] 636 | 637 | Example 4: 638 | Input: root = [1] 639 | Output: [1] 640 | 641 | Constraints: 642 | * The number of nodes in the tree is in the range [0, 100]. 643 | * -100 <= Node.val <= 100 644 | 645 | Follow up: Recursive solution is trivial, could you do it iteratively?*/ 646 | 647 | use std::rc::Rc; 648 | use std::cell::RefCell; 649 | impl Solution { 650 | pub fn inorder_traversal(root: Option>>) -> Vec { 651 | let mut ans = vec![]; 652 | let mut node = root; 653 | let mut stack = vec![]; 654 | while node.is_some() || !stack.is_empty() { 655 | if let Some(temp) = node { 656 | node = temp.borrow().left.clone(); 657 | stack.push(temp); 658 | } else { 659 | let temp = stack.pop().unwrap(); 660 | ans.push(temp.borrow().val); 661 | node = temp.borrow().right.clone(); 662 | } 663 | } 664 | return ans; 665 | } 666 | } 667 | 668 | 669 | /*100. Same Tree (Easy) 670 | Given the roots of two binary trees p and q, write a function to check if they 671 | are the same or not. Two binary trees are considered the same if they are 672 | structurally identical, and the nodes have the same value. 673 | 674 | Example 1: 675 | Input: p = [1,2,3], q = [1,2,3] 676 | Output: true 677 | 678 | Example 2: 679 | Input: p = [1,2], q = [1,null,2] 680 | Output: false 681 | 682 | Example 3: 683 | Input: p = [1,2,1], q = [1,1,2] 684 | Output: false 685 | 686 | Constraints: 687 | * The number of nodes in both trees is in the range [0, 100]. 688 | * -10^4 <= Node.val <= 10^4*/ 689 | 690 | use std::rc::Rc; 691 | use std::cell::RefCell; 692 | impl Solution { 693 | pub fn is_same_tree(p: Option>>, q: Option>>) -> bool { 694 | match (p, q) { 695 | (None, None) => true, 696 | (Some(p), Some(q)) => { 697 | let p = p.borrow(); 698 | let q = q.borrow(); 699 | p.val == q.val 700 | && Self::is_same_tree(p.left.clone(), q.left.clone()) 701 | && Self::is_same_tree(p.right.clone(), q.right.clone()) 702 | } 703 | _ => false, 704 | } 705 | } 706 | } 707 | 708 | 709 | /*104. Maximum Depth of Binary Tree (Easy) 710 | Given the root of a binary tree, return its maximum depth. A binary tree's 711 | maximum depth is the number of nodes along the longest path from the root node 712 | down to the farthest leaf node. 713 | 714 | Example 1: 715 | Input: root = [3,9,20,null,null,15,7] 716 | Output: 3 717 | 718 | Example 2: 719 | Input: root = [1,null,2] 720 | Output: 2 721 | 722 | Constraints: 723 | * The number of nodes in the tree is in the range [0, 10^4]. 724 | * -100 <= Node.val <= 100*/ 725 | 726 | use std::rc::Rc; 727 | use std::cell::RefCell; 728 | impl Solution { 729 | pub fn max_depth(root: Option>>) -> i32 { 730 | let mut ans = 0; 731 | let mut stack = vec![(root, 1)]; 732 | while let Some((node, depth)) = stack.pop() { 733 | if let Some(node) = node { 734 | let node = node.borrow(); 735 | ans = ans.max(depth); 736 | stack.push((node.left.clone(), depth+1)); 737 | stack.push((node.right.clone(), depth+1)); 738 | } 739 | } 740 | return ans; 741 | } 742 | } 743 | 744 | 745 | /*108. Convert Sorted Array to Binary Search Tree (Easy) 746 | Given an integer array nums where the elements are sorted in ascending order, 747 | convert it to a height-balanced binary search tree. 748 | 749 | Example 1: 750 | Input: nums = [-10,-3,0,5,9] 751 | Output: [0,-3,9,-10,null,5] 752 | Explanation: [0,-10,5,null,-3,null,9] is also accepted: 753 | 754 | Example 2: 755 | Input: nums = [1,3] 756 | Output: [3,1] 757 | Explanation: [1,null,3] and [3,1] are both height-balanced BSTs. 758 | 759 | Constraints: 760 | * 1 <= nums.length <= 10^4 761 | * -10^4 <= nums[i] <= 10^4 762 | * nums is sorted in a strictly increasing order.*/ 763 | 764 | use std::rc::Rc; 765 | use std::cell::RefCell; 766 | impl Solution { 767 | fn help(lo: i32, hi: i32, nums: &Vec) -> Option>> { 768 | if lo == hi { 769 | return None; 770 | } 771 | let mid = lo + hi >> 1; 772 | let mut node = TreeNode::new(nums[mid as usize]); 773 | node.left = Self::help(lo, mid, nums); 774 | node.right = Self::help(mid+1, hi, nums); 775 | return Some(Rc::new(RefCell::new(node))); 776 | } 777 | 778 | pub fn sorted_array_to_bst(nums: Vec) -> Option>> { 779 | let n = nums.len() as i32; 780 | return Self::help(0, n, &nums); 781 | } 782 | } 783 | 784 | 785 | /*110. Balanced Binary Tree (Easy) 786 | Given a binary tree, determine if it is height-balanced. 787 | 788 | Example 1: 789 | Input: root = [3,9,20,null,null,15,7] 790 | Output: true 791 | 792 | Example 2: 793 | Input: root = [1,2,2,3,3,null,null,4,4] 794 | Output: false 795 | 796 | Example 3: 797 | Input: root = [] 798 | Output: true 799 | 800 | Constraints: 801 | * The number of nodes in the tree is in the range [0, 5000]. 802 | * -10^4 <= Node.val <= 10^4*/ 803 | 804 | use std::rc::Rc; 805 | use std::cell::RefCell; 806 | impl Solution { 807 | fn calc(node: Option>>) -> i32 { 808 | match node { 809 | Some(node) => { 810 | let lv = Self::calc(node.borrow().left.clone()); 811 | let rv = Self::calc(node.borrow().right.clone()); 812 | return if lv == -1 || rv == -1 || (lv-rv).abs() > 1 {-1} else {1 + lv.max(rv)}; 813 | } 814 | None => 0 815 | } 816 | } 817 | pub fn is_balanced(root: Option>>) -> bool { 818 | return Self::calc(root) >= 0; 819 | } 820 | } 821 | 822 | 823 | /*111. Minimum Depth of Binary Tree (Easy) 824 | Given a binary tree, find its minimum depth. The minimum depth is the number of 825 | nodes along the shortest path from the root node down to the nearest leaf node. 826 | Note: A leaf is a node with no children. 827 | 828 | Example 1: 829 | Input: root = [3,9,20,null,null,15,7] 830 | Output: 2 831 | 832 | Example 2: 833 | Input: root = [2,null,3,null,4,null,5,null,6] 834 | Output: 5 835 | 836 | Constraints: 837 | * The number of nodes in the tree is in the range [0, 10^5]. 838 | * -1000 <= Node.val <= 1000*/ 839 | 840 | use std::rc::Rc; 841 | use std::cell::RefCell; 842 | impl Solution { 843 | pub fn min_depth(root: Option>>) -> i32 { 844 | match root { 845 | Some(node) => { 846 | let left = Self::min_depth(node.borrow().left.clone()); 847 | let right = Self::min_depth(node.borrow().right.clone()); 848 | if left == 0 || right == 0 { 849 | return 1 + left.max(right); 850 | } else { 851 | return 1 + left.min(right); 852 | } 853 | }, 854 | None => 0 855 | } 856 | } 857 | } 858 | 859 | 860 | /*112. Path Sum (Easy) 861 | Given the root of a binary tree and an integer targetSum, return true if the 862 | tree has a root-to-leaf path such that adding up all the values along the path 863 | equals targetSum. A leaf is a node with no children. 864 | 865 | Example 1: 866 | Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22 867 | Output: true 868 | Explanation: The root-to-leaf path with the target sum is shown. 869 | 870 | Example 2: 871 | Input: root = [1,2,3], targetSum = 5 872 | Output: false 873 | Explanation: There are two root-to-leaf paths in the tree: 874 | (1 --> 2): The sum is 3. 875 | (1 --> 3): The sum is 4. 876 | There is no root-to-leaf path with sum = 5. 877 | 878 | Example 3: 879 | Input: root = [], targetSum = 0 880 | Output: false 881 | Explanation: Since the tree is empty, there are no root-to-leaf paths. 882 | 883 | Constraints: 884 | * The number of nodes in the tree is in the range [0, 5000]. 885 | * -1000 <= Node.val <= 1000 886 | * -1000 <= targetSum <= 1000*/ 887 | 888 | use std::rc::Rc; 889 | use std::cell::RefCell; 890 | impl Solution { 891 | pub fn has_path_sum(root: Option>>, target_sum: i32) -> bool { 892 | let mut stack = vec![(root, 0)]; 893 | while let Some((node, mut v)) = stack.pop() { 894 | if let Some(node) = node { 895 | let node = node.borrow(); 896 | v += node.val; 897 | if node.left.is_none() && node.right.is_none() && v == target_sum { 898 | return true; 899 | } 900 | stack.push((node.left.clone(), v)); 901 | stack.push((node.right.clone(), v)); 902 | } 903 | } 904 | return false; 905 | } 906 | } 907 | -------------------------------------------------------------------------------- /leetcode.sh: -------------------------------------------------------------------------------- 1 | # 192. Word Frequency (Medium) 2 | # 3 | # Write a bash script to calculate the frequency of each word in a text file words.txt. 4 | # 5 | # For simplicity sake, you may assume: 6 | # words.txt contains only lowercase characters and space ' ' characters. 7 | # Each word must consist of lowercase characters only. 8 | # Words are separated by one or more whitespace characters. 9 | # 10 | # Example: 11 | # Assume that words.txt has the following content: 12 | # 13 | # the day is sunny the the 14 | # the sunny is is 15 | # 16 | # Your script should output the following, sorted by descending frequency: 17 | # 18 | # the 4 19 | # is 3 20 | # sunny 2 21 | # day 1 22 | # 23 | # Note: 24 | # Don't worry about handling ties, it is guaranteed that each word's frequency count is unique. 25 | # Could you write it in one-line using Unix pipes? 26 | 27 | tr -s ' ' '\n' < words.txt | sort | uniq -c | sort -r | awk '{print $2, $1}' 28 | 29 | # 193. Valid Phone Numbers (Easy) 30 | # 31 | # Given a text file file.txt that contains list of phone numbers (one per line), 32 | # write a one liner bash script to print all valid phone numbers. 33 | # 34 | # You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) 35 | 36 | # You may also assume each line in the text file must not contain leading or trailing white spaces. 37 | 38 | # Example: 39 | 40 | # Assume that file.txt has the following content: 41 | 42 | # 987-123-4567 43 | # 123 456 7890 44 | # (123) 456-7890 45 | # Your script should output the following valid phone numbers: 46 | 47 | # 987-123-4567 48 | # (123) 456-7890 49 | --------------------------------------------------------------------------------